#6909 closed bug (worksforme)
"this" is wrong in $(selector).each(function(){...})
Reported by: | luxigo | Owned by: | |
---|---|---|---|
Priority: | Milestone: | 1.4.3 | |
Component: | unfiled | Version: | 1.4.2 |
Keywords: | this closure | Cc: | |
Blocked by: | Blocking: |
Description (last modified by )
"this" is not what expected in $(selector).each(function(){...}) called from an event handler bound with $(selector).bind('event',function(){handler(this,data)})
Change History (4)
comment:1 Changed 12 years ago by
comment:2 Changed 12 years ago by
- Outside of the $(_this).find('.subtag').each(), this==window
- Inside the each(), this==_this && _this.className!='.subtag' (!?!?)
comment:3 Changed 12 years ago by
Description: | modified (diff) |
---|---|
Resolution: | → worksforme |
Status: | new → closed |
A function called from within the event handler gets a this
object based on the way you call it. If you call it like func(args)
then this==window
. You either need to pass the event handler's this
to the function, as you've done, or remove the _this argument in collapsable_toggle and its this
to the same as the event handler by using Function.call or Function.apply:
collapsable_toggle.call(this, '.subtag');
This is not a bug. If you need help with Javascript and jQuery, ask on the forum: http://forum.jquery.com
comment:4 Changed 12 years ago by
It is a bug, you dont understand the problem.
My fault, I should have named "_this" "elem" instead to avoid confusion.
The problem is not "this==window" in function collapsable_toggle() namespace (it is normal since collapsable_toggle is not a method of $('.tag')[] elements and i dont call the function with this.collapsable_toggle(selector).)
The problem is "this != $(elem).find(selector)[n]" in the (elem).find(selector).each() namespace, where "this==elem" instead.
It is weird because in the parent namespace of .each() (collapsable_toggle) "this==window": if it was equal to window it would be a closure problem, but since "this=elem" (ie: this from the parent namespace of the parent namespace of each()) it is a jQuery or javascript bug.
Wait... I build a html example with http://pastie.org/1096449 and surprise: it works ?!?!?
This is really weird -> I had the same bug on Firefox and Chrome yesterday, but today everything works.
Waste of time, sorry :-) Next time I record a screencast...
but "this" works:
http://pastie.org/1096483