I have a base class for all views and then in each section of the app, like profiles, I also have a base class. That way shared templates and properties can be used throughout my app on many levels.
I know that if you make the event property in a Backbone view a function instead of an object literal, it will be instantiated for you, I'm not sure how to use this to my advantage, though. My question is, what's the best way to automatically extend events created in a base view.
I know one possibility where I, on view initialize, fetch the base event class and extend my current event on to it, but it seems a little hacky, and I would have to duplicate this code on every view. If you know a better way please share.
Thanks.
var ParentView = Backbone.View.extend({
'events': {
'click .parent-something': "onParentSomethingClick"
}
});
var ChildView = ParentView.extend({
'events': _.extend({
'click .something': 'onSomethingClick',
}, ParentView.prototype.events)
});
It's not doing nothing, but it's the simplest way I've seen so far.
I've also created a gist on another way I've been using: https://gist.github.com/1271041
Here's how I extend the parent view's events in my child view:
var ParentView = Backbone.View.extend({
events: {
'click .link': 'onLinkClick'
}
});
var ChildView = ParentView.extend({
events: function(){
return _.extend({
'click .something': 'onSomethingClick',
}, this.constructor.__super__.events);
}
});
Note: this only works as of Backbone 0.5.3. Before that version, you couldn't define events as a function.
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