Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing functions to the `events` hash

Tags:

backbone.js

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?

like image 735
Randomblue Avatar asked Jan 23 '26 23:01

Randomblue


1 Answers

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);
}
like image 117
mu is too short Avatar answered Jan 25 '26 13:01

mu is too short