Skip to main content

Bug Tracker

Side navigation

#6909 closed bug (worksforme)

Opened August 16, 2010 10:00PM UTC

Closed August 17, 2010 01:40AM UTC

Last modified August 17, 2010 07:56AM UTC

"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:

"this" is not what expected in $(selector).each(function(){...}) called from an event handler bound with $(selector).bind('event',function(){handler(this,data)})

Attachments (0)
Change History (4)

Changed August 16, 2010 10:11PM UTC by luxigo comment:1

but "this" works:

Changed August 16, 2010 10:35PM UTC by luxigo comment:2

  • Outside of the $(_this).find('.subtag').each(), this==window
  • Inside the each(), this==_this && _this.className!='.subtag' (!?!?)

Changed August 17, 2010 01:40AM UTC by dmethvin comment:3

description: \ "this" is not what expected in $(selector).each(function(){...}) called from an event handler bound with $(selector).bind('event',function(){handler(this,data)}) \ \ \ "this" is not what expected in $(selector).each(function(){...}) called from an event handler bound with $(selector).bind('event',function(){handler(this,data)}) \ \ \
resolution: → worksforme
status: newclosed

A function called from within the event handler gets a

object based on the way you call it. If you call it like
. You either need to pass the event handler's
to the function, as you've done, or remove the _this argument in collapsable_toggle and its
to the same as the event handler by using or Function.apply:, '.subtag');

This is not a bug. If you need help with Javascript and jQuery, ask on the forum:

Changed August 17, 2010 07:56AM UTC by luxigo comment:4

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 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...