I’m trying to add a BaseView that performs some initialization for all Backbone views in my Module.
Here’s a fiddle and the code is reproduced below
Creating a custom BaseView and having it subscribe to the ‘close’ event on the dispatcher. So as to have it be a part of all children on creation.
var dispatcher = _.clone(Backbone.Events);
var ctor = Backbone.View;
var BaseView = Backbone.View.extend({
//override Backbone's constructor
constructor: function(options) {
ctor.apply(this, arguments);
dispatcher.on('close', this.close, this);
},
close: function() {
console.log(this.cid);
}
});
//Is this really needed??
BaseView.prototype.constructor = Backbone.View;
Creating a child view inheriting from BaseView:
var View = BaseView.extend({
el: '#clickholder',
initialize: function() {
_.bindAll(this);
},
//Events not bound?
events: {
"click #clicker": "clicked"
},
//never called :(
clicked: function(e) {
alert("clicked button");
}
});
new View();
and here’s the HTML:
<div id="clickholder">
<button id="clicker">Clicker</button>
</div>
Question: If the button is clicked, the event is never fired and the alert is never shown. I’m not sure what the problem is. I’ve spent quite a while on it but can’t fathom why is events not getting bound to the View? What am I doing wrong?
PS: This is based on the answer here. I specifically created a BaseView class so as to not have this globally effect all Backbone Views across my application but just keep it restricted to the specific module
UPDATE: fixed fiddle as per @mu’s answer below. Wrapping the button in a div doesn’t seem to solve the problem either. I erroneously had the view be bound to the button directly for simplification. In my main application the button is “within” the view’s el so delegation worked just fine “before” the above BaseView was put into place.
You have a few problems:
<head>so there is no#clickerwhen it runs so there’s nothing to bind the events to.Your view’s
elis supposed to be#clickerbut your event is trying to bind to#clickerinsideel. From the fine manual:If you want to bind to a click on
el, then you want:Updated demo: http://jsfiddle.net/ambiguous/fTrSj/