I have a generic subclass of Backbone.View which has a close event listener.
var GenericView = Backbone.View.extend({
events : {
"click .close" : "close"
},
close : function () {
console.log("closing view");
}
});
I want to subclass this generic class and add some new events. However the below will overwrite the super classes (above) event object. E.g.
var ImplementedView = new GenericView({
// setting this will stop 'close' in Super Class from triggering
events : {
"click .submit" : "submit"
}
});
How should I create a sub class, in this case ImplementedView and retain the events?
I have found one way to achieve this, by extending the event object when the child class is constructed. However I need to re-trigger this.delegateEvents(), which I am guessing is not good. Can any one comment on this?
var ImplementedView = new GenericView({
initialize : function (options) {
_.extend(this.events, {
"click .submit" : "submit"
});
// re-attach events
this.delegateEvents();
}
});
@Nupul is exactly right: you’re not subclassing your
GenericView.In fact, subclassing isn’t really the right word here, since JavaScript doesn’t do classical inheritance.
So let’s first try and understand what’s happening here:
Backbone.Viewis a constructor function, that when called with thenewkeyword, creates a new object for you.Since this is JS, all function are really function objects, so
Backbone.View.extendis just a function hanging offBackbone.Viewthat does a few things:GenericView) to instantiate objects of your inheriting classSo the correct way to set up the protoype chain you want is:
and NOT:
because this just creates a new instance of a GenericView.
Now, you still have a problem, because when you do something like:
At this point there are different ways to get the result you want, here’s one that uses
delegateEventskind of like how you did. Using it isn’t bad, incidentally.