删除一个JQuery小部件实例的事件处理程序

时间:2013-11-18 14:57:22

标签: jquery jquery-ui javascript-events

我使用JQuery UI小部件工厂编写了一个小部件(在typescript中)。

我的窗口小部件侦听窗口元素上的滚动事件,因此在_create函数中添加了一个事件处理程序:

_create = function () {
   $(window).on("scroll", this.handleScroll);
}

在_destroy函数中我想删除处理程序:

_destroy = function () {
   $(window).off("scroll", this.handleScroll);
}

但是,我的页面上可能有两个这个小部件的实例:一个在常规页面中,另一个在弹出窗口中。我当前的实现删除了两个实例的处理程序,这显然是不需要的。

我已经阅读了这个问题:Recommended way to remove events on destroy with jQuery UI Widget Factory,接受的答案适用于自定义事件,但我看不到像'scroll'这样的标准事件的解决方案。

任何想法都赞赏。

2 个答案:

答案 0 :(得分:3)

该解决方案也适合您。如果您还没有它们,请在页面和弹出窗口中为您的小部件指定ID。然后,修改你的代码:

_create = function () {
   $(window).on("scroll." + this.id, this.handleScroll);
}

_destroy = function () {
   $(window).off("scroll." + this.id, this.handleScroll);
}

请注意“。”在调用on()和off()之后滚动。请参阅此文章:Namespaced events in jquerythis one

答案 1 :(得分:1)

你提到的答案也适用于你的情况。你可以尝试这样的事情。

_create = function () {
   $(window).on("scroll." + this.id, this.handleScroll);
}

$(window).off('scroll.' + this.id);
相关问题