Welcome to Code Couch

Replacement for “bind” or “bindAsEventListener” in jQuery

Posted by at 8:21pm on December 15, 2008.

After working for many years with the Prototype JS framework, I decided it was time to bite the bullet and learn jQuery.

There were 3 reasons, really… 1: I’ve just started a new project and don’t need most of the bloat Prototype comes with; 2: I can now make a judgement call when it comes to choosing a framework; and 3: It’s another skill on my CV :o)

I’ve just spent the weekend reading jQuery in Action cover-to-cover, and I can highly recommend it for intermediate or advanced developers looking to see what it offers.

The one thing I miss from Prototype however are the “bind” and “bindAsEventListener” commands which can set the context (“this”) of the callback – in my case, the instance of a class.

After a bit of searching, I found this post by Andreas Gohr. It was coderjoe’s comment that set the wheels in motion. He showed that you could rewrite this Prototype code:

initialize: function() {
	Event.observe(someEl, 'click',
		this.doSomething.bindAsEventListener(this)
	);
}

as this jQuery code:

init: function() {
	var self = this;
	$(someEl).bind('click', function(eventData) {
		self.doSomething(eventData, self);
	});
}

The bind (and related) method allows you to pass three parameters, however: the event type, some data, and a callback function. If the data parameter is omitted, the callback can be put as the second parameter.

So, we can re-write that last example using the second data parameter, removing the need to set a scoped variable:

init: function() {
	jQuery(someEl).bind('click', {thisContext:this}, function(eventData) {
		eventData.data.thisContext.doSomething(eventData);
	});
}

Post to Twitter

Tags: , , ,

Comments

There are no responses to this post.

Leave a reply

Comments are closed for this post.