更新
I didn't want to bring this out unless really necessary, but if you really want this to apply to all view instances, without the need to have them descend from your own custom base view class, you can try something like this (overriding Backbone.View
, the built-in base view class constructor):
http://jsfiddle.net/D9gR7/5/
$( document ).ready( function () {
// Create your actual object here
var dispatcher = _.clone( Backbone.Events );
( function () {
var ctor = Backbone.View;
Backbone.View = Backbone.View.extend( {
constructor : function ( options ) {
ctor.apply( this, arguments );
dispatcher.on( 'close', this.close, this );
},
// constructor
close : function () {
console.log( this.cid );
}
// close
} );
Backbone.View.prototype.constructor = Backbone.View;
} )();
var View = Backbone.View.extend( {} );
var views = [];
var i;
for ( i = 0 ; i < 10 ; ++i ) {
views.push( new Backbone.View );
}
for ( i = 0 ; i < 10 ; ++i ) {
views.push( new View );
}
dispatcher.trigger( 'close' );
} );
Original Answer
There are a bunch of issues with your code. What about something like this (see the console for output, obviously)? I think this is pretty much what you're going for. You'd just need to make sure you call the parent initialize()
when you override the method in sub classes. Also, if you want to completely blow away the view instances at some point, make sure you call dispatcher.off( null, null, view_instance )
.
http://jsfiddle.net/D9gR7/
$( document ).ready( function () {
// Create your actual object here
var dispatcher = _.clone( Backbone.Events );
var View = Backbone.View.extend( {
initialize : function ( options ) {
dispatcher.on( 'close', this.close, this );
},
close : function () {
console.log( this.el.id );
}
} );
var Some_Kind_Of_View = View.extend( {
initialize : function ( options ) {
View.prototype.initialize.apply( this, arguments );
// ...
}
} );
var view1 = new View( {
el : $( "#MyDiv" )[0],
} );
var view2 = new Some_Kind_Of_View( {
el : $( "#MyDiv2" )[0]
} );
dispatcher.trigger( 'close' );
} );
Some issues with your example code:
var V1 = Backbone.View.extend({
// JMM: If you pass `el` to `extend()`, any instances you create
// from the class will be tied to the same DOM element, unless
// you pass a different `el` to the view constructors. Maybe
// that's what you want.
el: '#MyDiv',
initialize: function() {
var self = this;
// JMM: You're assigning `undefined` to this prototype
// property. And you're trying to register the
// return value of self.alert() (`undefined`) as
// the handler for the `olay` event.
Backbone.View.prototype.subOnClose = (function(){
model.on('olay',self.alert('olay'));
})();
},
alert: function(s) {
alert('V1 -->' + s);
}
});