How does the new hash of the Backbone View heading "events" work with function values ​​instead of strings in version 0.9.0?

Backbone 0.9.0 Summary says:

The hash representation of events can now also contain direct function values ​​as well as string names of existing view methods.

When I try to do the following, it fails, stating 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() 

Do I really not understand the new feature? Can someone explain how this works differently than I expected? Perhaps this is just my javascript syntax / value for 'this' during borked definition.

The way I'm used to doing this works:

 'events': { 'click input[type="button"]': 'buttonClicked' }, 
+7
source share
1 answer

When the JavaScript parser gets here:

 'events': { 'click input[type="button"]': this.buttonClicked }, 

this is probably a window , not a BB instance, as you would expect. The window object does not have a buttonClicked property (at least in your case it is not), so you really say that:

 'events': { 'click input[type="button"]': undefined }, 

and there is your mistake.

If you look at the source of delegateEvents , you will see what 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 interests you. This means that you can say these things:

 events: { 'click input[type="button"]': function() { alert('pancakes!') }, 'click button': some_function_that_is_in_scope } 

Thus, you can put certain functions (either by their name, if available, or as function literals) in the events lookup table.

+14
source

All Articles