Skip to main content

Bug Tracker

Side navigation

#8355 closed bug (invalid)

Opened February 22, 2011 09:56PM UTC

Closed February 23, 2011 11:44AM UTC

Last modified February 23, 2011 12:11PM UTC

Context of $.proxy callbacks: different when chained

Reported by: Cecile Muller <wildpeaks@googlemail.com> Owned by:
Priority: undecided Milestone: 1.next
Component: unfiled Version: 1.5
Keywords: Cc:
Blocked by: Blocking:
Description

Live example

http://jsfiddle.net/3Y9vk/

(uses console.log to display the difference)


An object class (a.k.a. a function used to create typed objects) implements this public method:

function bind(eventName, handler){
	return element.bind(eventName, $.proxy(handler, context));
};
  • "element" is a detached DOM element used to send events from
  • "context" is a reference to the class instance.


Therefore the instance/object can be used the following way, which works fine:

myObj.bind("custom_event1", oncustom1)
myObj.bind("custom_event2", oncustom2);


However if both .bind are chained, the context is different despite the function of the object returns the value of element.bind: both callbacks are called, however the second callback receives "element" as context while the first callback receives "myObj" as context.

myObj
 .bind("custom_event1", oncustom1)
 .bind("custom_event2", oncustom2);


The behavior is consistent among browsers and acts the same in all jQuery versions from 1.4 to 1.5.

Attachments (0)
Change History (3)

Changed February 22, 2011 10:10PM UTC by Cecile Muller <wildpeaks@googlemail.com> comment:1

I forgot ";" at the end of the first line of the second code block (but that typo is only in the ticket, not in the jsfiddle example).

Changed February 23, 2011 11:44AM UTC by jitter comment:2

resolution: → invalid
status: newclosed

Thanks for taking the time to contribute to the jQuery project by writing a bug report and providing a test case!

After checking your report and test case I fail to see how this is a jQuery bug. Your custom bind() function returns a jQuery object. So when chaining, the first bind() call goes to your function, while the second call goes to the jQuery .bind().

You probably mean to do this in your bind() code.

...
   element.bind(eventName, $.proxy(handler, context))
   return this;
...

Also check this modified test case

Changed February 23, 2011 12:11PM UTC by Cecile Muller <wildpeaks@googlemail.com> comment:3

I wasn't sure how ''bind'' stores the association internally, hence the reason why I was returning directly the value of ''element.bind'' in the hope to interfer the least on jQuery's events.

But you're right, returning ''this'' instead of the return value of element.bind sends the right context in both cases, great :-)