Event delegation in Backbone views

I ran into an issue recently on a project using Backbone.js. It’s a great library but I ran into some unexpected behavior when binding events. I’ve submitted this pull request but if you’re having difficulty binding events to Backbone views (v0.5.3) this info may help you out.

If you attempt to do something like this:


function btnClick(){
console.log(':(');
//BTW I DO exist
}
var v = Backbone.View.extend({
el : "#page",
events : {"click .btn" : btnClick}
});

You will get this error:

line :958 of backbone-0.5.3.js
Uncaught Error: Event "function btnClick(){
console.log(':(');
//BTW I DO exist
}" does not exist

This error is particularly odd because it shows you the function body you want and then claims it doesn’t exist. I’m pretty sure we can all agree that it does exist which is why I think this may just be a oversight. Especially considering that the fix I submitted is only a half a line long. This minor modification to line 958 opens up more possibilities.

- var method = this[events[key]];
+ var method = this[events[key]] || events[key];

With this modification you can use a function confided to a clouser:

(function(){
function btnClick(){
console.log("You'll never overwite me :)");
}
var v = Backbone.View.extend({
el : "#page",
events : {"click .btn" : btnClick}
});
})();

Or you could use functions from some preferred library, directly without over complicating things.

this:
var v = Backbone.View.extend({
el : "#page",
events : {"click .btn" : theBestLibraryEver.awesome }
});

or this:
var v = Backbone.View.extend({
el : "#page",
events : {"click .btn" : "extraneous" }
extraneous : function(){
theBestLibraryEver.awesome.apply(this, arguments);
}
});

Which is your choice?

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s