我在应用程序中有一些小部件,在创建/初始化时会将一系列事件处理程序附加到主容器元素。
widget = function(){
this.el = $("#someelement");
this.init = function(){
doAjax(function(data)){
this.el.html(data)
.on("click", function(){
//attach some handler here
})
.on("change", ("div.class"), function(){
//attach some handler here
});
}
}
this.reload = function(){
this.init();
}
}
我的问题在这里很明显 - 每当我重新加载小部件(调用init函数)时,我都会将处理程序重新附加到元素上。然后,如果我触发一个处理程序,它会完成我已经“刷新”的次数。我尝试过多种方法:
this.el.empty().html(data)
this.el.off("*").html(data)
this.el.html(data)
.off("click change")
this.el.children.remove().end().html(data)
等等。我没做什么实际上删除了事件处理程序。我所能做的就是追加/添加它们。我永远无法清除它们。我做错了什么?
答案 0 :(得分:1)
widget = function(){
this.el = $("#someelement");
this.isInitialLoad = false;
this.init = function(){
doAjax(function(data)){
if(!isInitialLoad){
this.el.html(data)
.on("click", function(){
//attach some handler here
})
.on("change", ("div.class"), function(){
//attach some handler here
});
}
else {
this.el.html(data);
}
}
}
this.reload = function(){
this.init();
}
}
或者,分离问题:
widget = function(){
this.el = $("#someelement");
this.init = function(){
doAjax(function(data) {
this.el.html(data)
.on("click", function(){
//attach some handler here
})
.on("change", ("div.class"), function(){
//attach some handler here
});
});
}
this.reload = function(){
doAjax(function(data) { this.el.html(data); });
}
}