Inside Backbone.View instances one can set an events hash of callbacks:
events: { 'click #element' : 'myFunction' }
When the function I try to access is not a direct function of the view instance (e.g. this.model.myFunction) I cannot pass the function right in the events hash. I have tried:
events: { 'click #element' : 'model.myFunction' }
and
events: { 'click #element' : this.model.myFunction }
How can I tell my backbone view to use this.model.myFunction as a callback right from the events hash?
No, you can't do that. The relevant chunk of Backbone looks like this:
delegateEvents : function(events) {
if (!(events || (events = getValue(this, 'events')))) return;
this.undelegateEvents();
for (var key in events) {
var method = this[events[key]];
if (!method) throw new Error('Event "' + events[key] + '" does not exist');
//...
So the values in events have to be the names of methods in your view object. You could route the events yourself though:
events: { 'click #element': 'myFunction' },
// ...
myFunction: function(e) {
this.model.myFunction(e);
}
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