アップデート
本当に必要でない限り、これを持ち出したくありませんでしたが、これをすべてのビュー インスタンスに適用したい場合は、独自のカスタム ベース ビュー クラスから派生させる必要はありませんBackbone.View
。組み込みの基本ビュー クラス コンストラクター):
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' );
} );
元の回答
あなたのコードにはたくさんの問題があります。このようなものはどうですか (出力についてはコンソールを参照してください)。私はこれがあなたがしようとしていることだと思います。initialize()
サブクラスでメソッドをオーバーライドするときは、必ず親を呼び出す必要があります。また、ある時点でビュー インスタンスを完全に吹き飛ばしたい場合は、必ず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' );
} );
サンプルコードに関するいくつかの問題:
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);
}
});