バックボーンに作成されたビュー (リスト コンテナー) があり、いくつかのイベントを処理する複数のビュー アイテム (セクション) を含める必要があります。このシナリオの問題は、サブビュー アイテムがコンテナー内に配置されるたびにイベントが実行されることです。
closeSection メソッドを Container ビューに配置すれば、この影響を防ぐことができることはわかっていますが、完全な作業ビューに焦点を当てた場所は間違っていると思います。
Backbone.js コンテキストでこの問題を解決するための最良の解決策は何ですか?
例:
// The Container View (simplified)
var Container = Backbone.View.extend({
el:$('#someDivContainer'),
render:function(){
$(this.el).html('<div id="head"></div><div id="sections"></div>');
return this;
}
});
// The subview (simplified)
var subView = backbone.View.extend({
template:_template('<div><div class="scthd"><a class="op_cl">x</a></div><div><%- content %></div></div>');
events:{
'click a.op_cl':'closeSection'
},
initialize:function(){
this.setElement($('#sections');
},
closeSection:function(event){
event.preventDefault();
console.log('event was triggered');
},
render:function(){
$(this.el).append(this.template({content:'Test ' + i});
return this;
}
});
var oContainer = new Container();
oContainer.render().el;
// These produces a ten time event execution by a click on one a.op_cl item
for(var i=0; i<10; i+=1){
var oSubView = new subView();
oSubView.render().el;
}
「最終」出力は次の例のようになります。
<!-- The HTMl of the first view -->
<div id="head"></div>
<div id="sections">
<div>
<div class="scthd">
<a class="op_cl">x</a>
</div>
<div>Test 0</div>
</div>
<div>
<div class="scthd">
<a class="op_cl">x</a>
</div>
<div>Test 1</div>
</div>
<div>
<div class="scthd">
<a class="op_cl">x</a>
</div>
<div>Test 2</div>
</div>
<div>
<div class="scthd">
<a class="op_cl">x</a>
</div>
<div>Test n</div>
</div>
</div>
事前にTHX。