Meshaal
Meshaal

Reputation: 704

Unbind events from all namespaces except a particular one

If I bind a jQuery scroll event handler to a particular namespace…

$(window).on('scroll._my_namespace',function() { ... });

…is there any way to then unbind all scroll event handlers except the ones assigned to that namespace? For example, if I do…

$(window).off('scroll._my_namespace');

…it would unbind that specific scroll handler, and if I do…

$(window).off('scroll');

…it would unbind all scroll handlers.

What I've tried so far:

$(window).off('scroll.'); // Doesn't seem to do anything

Never expected this to work, but figured I'd better try it before posting:

$(window).off('scroll:not("._my_namespace")'); // Also doesn't do anything

What I want to do is unbind all scroll event handlers except the one assigned to a specific namespace. Is there some way to do this?

Upvotes: 3

Views: 821

Answers (2)

pyb
pyb

Reputation: 5269

Loop through your namespaces and call off for each of them but he one you don't want.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

I don't know any way using the public apis other than to have another common namespace for all the handlers that has to be removed.

But using the private events collection you can try something like

var events = $._data(window, 'events');
for (var i = events.scroll.length - 1; i >= 0; i--) {
    var handler = events.scroll[i];
    if (handler && handler.namespace != 'ns') {
        $(window).off('scroll', handler.handler)
    }
}

$(window).on('scroll.ns', function(e) {
  console.log('x', e.type, e.handleObj.namespace, e)
});
$(window).on('scroll.ns2', function(e) {
  console.log('y', e.type, e.handleObj.namespace, e)
});
$(window).on('scroll.t', function(e) {
  console.log('z', e.type, e.handleObj.namespace, e)
});

$('button').click(function() {
  var events = $._data(window, 'events');
  for (var i = events.scroll.length - 1; i >= 0; i--) {
    var handler = events.scroll[i];
    if (handler && handler.namespace != 'ns') {
      $(window).off('scroll', handler.handler)
    }
  }
});
body {
  height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>Remove</button>

Upvotes: 3

Related Questions