[英]Unbind events from jQuery handler
我正在嘗試解決舊系統,本質上是在某種情況下劫持了一個提交按鈕,對其應用了一個處理程序,然后在完成后取消綁定該處理程序。 我正在使用bind
和unbind
但是每次啟動有問題的表單時,事件都會被累積綁定。
class MyForm(){
constructor(){
// button in question
this.$submit = $('#submit');
this.$submit.bind('click', this.submit.bind(this));
return this;
}
submit(){
return this.doAjaxStuff();
}
doAjaxStuff(){
var self = this;
return $.post(file, data).always(function(){
self.$submit.unbind('click', self.submit);
});
}
}
不幸的是,每次我創建一個新的MyForm
,事件都會再次綁定,但是永遠不會解除綁定。
簡單的解決方法是先使用off()
並為事件命名空間。 刪除命名空間事件不會干擾同一事件的其他偵聽器
this.$submit.off('click.special').on('click.special', this.submit.bind(this));
請注意,不建議使用bind()
和unbind()
..使用on()
和off(0
代替。
更好的方法是在頁面加載后委托一次,而不是繼續調用同一類
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.