[英]Backbone bind event fired multiple times
我正在尝试使用主干js构建一个切换视图,并在我切换视图几次时发现我的多次绑定事件。
以下是更好地说明的代码:
HTML
<div id='container'>
halo world
</div>
<button id='but1'>red view</button>
<button id='but2'>blue view</button>
CSS
#red_view{
width:400px;
height:400px;
background-color:red;
}
#blue_view{
width:400px;
height:400px;
background-color:blue;
}
.button,.button2{
width:300px;
height:300px;
background-color:gray;
}
javascript
RedView = Backbone.View.extend({
el: "#container",
events:{"click .button":"clickme"},
clickme:function(){
alert('redview');
},
initialize: function(){
this.$el.html("<div id='red_view'><div class='button'>Click Me</div></div>");
}
});
BlueView = Backbone.View.extend({
el: "#container",
events:{"click .button2":"clickme2"},
clickme2:function(){
alert('blueview');
},
initialize: function(){
this.$el.html("<div id='blue_view'><div class='button2'>Click Me</div></div>");
}
});
$(document).ready(function(){
//var router = new SystemRouter();
$('#but1').click(function(){
var view = new RedView();
});
$('#but2').click(function(){
var view = new BlueView();
});
});
如果单击红色视图3次,然后按“单击我”。 它会弹出警报3次。 我怀疑有必要在某个地方取消绑定事件,但找不到合适的方法。 最好提供一些正确执行此操作的参考。
这是jsfiddle演示的链接。 http://jsfiddle.net/mochatony/DwRRk/31/
每次单击red view
或blue view
按钮时,每次都会创建一个新的红色或蓝色视图 。 您绑定的事件哈希响应单击从类别按钮发起DOM事件button
和button2
。
这是因为您在创建新视图之前不会清理视图,从而使您无法看到响应事件的ghost视图。 (有关事件哈希的更多信息)您可以使用类似的方式清除视图中的事件。
cleanup: function() {
this.undelegateEvents();
$(this.el).clear();
}
这是你工作清理视图的小提琴http://jsfiddle.net/DwRRk/34/
还有一个良好实践的提示:你应该使用类似渲染方法的东西将东西附加到你的DOM,使用初始化来初始化视图所需的值。
每次单击按钮时都会创建一个新视图,而不会破坏前一个视图。 尝试使用单个视图,如下所示:
var SomeModel = Backbone.Model.extend({});
var SomeView = Backbone.View.extend({
el: "#container",
model: SomeModel,
events: {
"click .button": "clickme"
},
clickme: function() {
alert(this.model.get("color"));
},
colorChanged: function() {
this.$el.html("<div id='" + this.model.get("color") + "_view'><div class='button'>Click Me</div></div>");
},
initialize: function() {
_.bindAll( this, "colorChanged" );
this.model.on("change:color", this.colorChanged );
this.model.on("reset", this.colorChanged );
}
});
$(document).ready(function() {
//var router = new SystemRouter();
var model = new SomeModel({color: "red"}),
view = new SomeView({model: model})
$('#but1').click(function() {
model.set("color", "red");
});
$('#but2').click(function() {
model.set("color", "blue");
});
});
这是删除幽灵视图的另一种方法(我正在使用的)
disposeView: function(view){
Backbone.View.prototype.close = function () {
this.unbind();
this.undelegateEvents();
};
/* --Destroy current view */
if(this.currentView !== undefined) {
this.currentView.close();
}
/* --Create new view */
this.currentView = view;
this.currentView.delegateEvents();
return this.currentView;
}
disposeView(new view());
请务必始终在您的视图中返回“this”,否则这将无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.