The Backbone 0.9.0 changelog says:
A view's events hash may now also contain direct function values as well as the string names of existing view methods.
When I try the following it fails, saying that the value for the event is undefined
.
var BB = Backbone.View.extend({
'initialize': function() {
this.$el.html('<input type="button" value="Click me!" />');
jQuery('body').html(this.el);
},
'events': {
'click input[type="button"]': this.buttonClicked
},
'buttonClicked': function() {
alert('button clicked!');
}
});
window.b = new BB()
Am I misunderstanding the new feature? Can somebody explain how it works differently than I expected? Perhaps it's just my JavaScript syntax/value of 'this' at definition time that is borked.
The way I'm used to doing it still works:
'events': {
'click input[type="button"]': 'buttonClicked'
},
Backbone. js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
js view class to create a custom view. Syntax: Backbone. View.
js Event once() The event once method is just like event on method but it causes the bound callback to only fire once before being removed.
The Backbone. js collection models specify the array or models which are created inside of a collection. Syntax: collection.
When the JavaScript parser gets here:
'events': {
'click input[type="button"]': this.buttonClicked
},
this
is probably window
, not an instance of BB
as you expect. The window
object doesn't have a buttonClicked
property (at least it doesn't in your case) so you're really saying this:
'events': {
'click input[type="button"]': undefined
},
and there's your error.
If you look at the source for delegateEvents
, you'll see what the ChangeLog means:
delegateEvents: function(events) {
// ...
for (var key in events) {
var method = events[key];
if (!_.isFunction(method)) method = this[events[key]];
// ...
}
},
That _.isFunction
call is what you're interested in. That means that you can say things like this:
events: {
'click input[type="button"]': function() { alert('pancakes!') },
'click button': some_function_that_is_in_scope
}
So you can put defined functions (either by their name if they're accessible or as function literals) in the events
lookup table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With