4

I've written a widget using the jQuery UI widget factory (in Typescript).

My widget listens for scroll events on the window element, so an event handler is added in the _create function:

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

And in the _destroy function I want to remove the handler:

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

However, there can be two instances of this widget on my page: one in the regular page, and one in a popup. My current implementation removes the handlers for both instances, which is clearly unwanted.

I've read this question: Recommended way to remove events on destroy with jQuery UI Widget Factory, the accepted answer there works fine for a custom event, but I cannot see a solution for a standard event like scroll.

Any ideas appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Moolie
  • 569
  • 2
  • 7
  • 17
  • See my answer below. If it works for you, you should accept so that this answer doesn't show up in the question stream of users logging in now. If it doesn't or if you need any clarifications, leave me a comment. – Chandranshu Nov 18 '13 at 15:09

2 Answers2

3

That solution will work for you too. If you don't have them already, assign ids to both your widgets - on the page and in the pop-up. Then, modify your code like this:

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

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

Please notice the "." after the scroll in the calls to on() and off(). See this article: Namespaced events in jquery and this one.

Chandranshu
  • 3,669
  • 3
  • 20
  • 37
  • Thanks, I didn't realize this worked for standard events as well. I made this the accepted answer, as your seems to be the first one seconds before roydukkey's answer :) – Moolie Nov 18 '13 at 15:17
  • Namespacing events is fantastic for complex apps with dynamic content. I used this for when tags were being added and removed in a selectize widget and I didn't have a function reference to remove the handler after removing the tag. This prevented memory leak issues. I never knew about namespacing events in jquery before. Awesome! – RoboBear Apr 17 '19 at 16:31
1

The answer you refer should work in your case as well. You could try something like this.

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

$(window).off('scroll.' + this.id);
roydukkey
  • 3,149
  • 2
  • 27
  • 43