I'm working on simple application with excelent framework Backbone.js and it will be nice if I could make configurable backbone view events selector for example this way it doesn't work, cause it's wrong js syntax:
return Backbone.View.extend({
events: {
'click ' + someConfigSelector: 'doSomethink'
}
})
Is there any other way to setup events in Backbone views?
Check out this fiddle: http://jsfiddle.net/phoenecke/hyLMz/1/
You can use a function for events
instead of an object.
return Backbone.View.extend({
events: function() {
// add some normal events to the hash
var e = {
'click #foo': 'doSomething1',
'click #bar': 'doSomething2'
};
// add one where key is calculated
e['click ' + someConfigSelector] = 'doSomething';
// return events hash
return e;
}
});
That way, you can add your events where the key is calculated based on your config.
I prefer the method below for dynamic events, as this function will be called any time delegateEvent
is called.
Per the docs on delegateEvent, which is called after the view's initialize
function is executed, you can use this technique to create the events dynamically:
var TestView = Backbone.View.extend({
events: function () {
var evt = {};
evt['click ' + this._extraSelector] = '_onButtonClick';
return evt;
},
initialize: function(config) {
// passed in the selector, or defaulted
this._extraSelector = config.extraSelector || "BUTTON.default";
},
_onButtonClick: function() { }
});
var v = new TestView({ extraSelector: 'BUTTON.sample' });
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