Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  74] [ 2]  / answers: 1 / hits: 22752  / 12 Years ago, wed, may 30, 2012, 12:00:00

I was wondering if it is possible to bind multiple event types in backbone within a single line.



Consider the following:



var MyView = Backbone.View.extend({
id: 'foo',
events: {
'click .bar': 'doSomething',
'touchstart .bar': 'doSomething'
},
doSomething: function(e) {
console.log(e.type);
}
});


Basically what I am wondering is if it is possible to combine the event binding for 'click' and 'touchstart' into one line - along the lines of:



events: { 'click,touchstart .bar': 'doSomething' }


Any suggestions would be appreciated.


More From » backbone.js

 Answers
3

For anyone interested I ended up overriding delegateEvents in Backbone.View.



There are only a few modified lines to get the desired functionality.



You can see a diff in my commit on github



Here is delegateEvents in its modified state:



delegateEvents: function(events) {
if (!(events || (events = getValue(this, 'events')))) return;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method)) method = this[events[key]];
if (!method) throw new Error('Method ' + events[key] + ' does not exist');
var match = key.match(delegateEventSplitter);
var eventTypes = match[1].split(','), selector = match[2];
method = _.bind(method, this);
var self = this;
_(eventTypes).each(function(eventName) {
eventName += '.delegateEvents' + self.cid;
if (selector === '') {
self.$el.bind(eventName, method);
} else {
self.$el.delegate(selector, eventName, method);
}
});
}
}

[#85274] Monday, May 28, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleyterryp

Total Points: 290
Total Questions: 92
Total Answers: 95

Location: Montenegro
Member since Sun, May 7, 2023
1 Year ago
;