Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Unbind $window of an event from specific directive

Tags:

angularjs

Inside one of my directives, I use angular.element($window).bind('scroll'). When the directive is destroyed, I then want to unbind it. Normally, I would just do:

$scope.$on('$destroy', function()
{
    angular.element($window).unbind('scroll');
});

But what if another directive also has binded to the scroll event of the $window, and that event still needs to exist. If I use the unbind above, the other directive's binding is also eliminated.

What are my options?

like image 877
Kousha Avatar asked Aug 22 '14 06:08

Kousha


2 Answers

Pass the same function reference to unbind/off as you pass to bind/on to unbind just that particular handler:

var fn = function () {};

angular.element($window).on('scroll', fn);

angular.element($window).off('scroll', fn);

For example:

var onScrollAction = function () {
  // Do something 
};

angular.element($window).on('scroll', onScrollAction);

scope.$on('$destroy', function () {

  angular.element($window).off('scroll', onScrollAction);
});

Note that in jQuery the functions bind and unbind are deprecated. You can however still use them both with jQuery and jqLite as they just call on and off behind the scenes.

like image 94
tasseKATT Avatar answered Nov 11 '22 20:11

tasseKATT


JQuery's on() supports namespacing events so they can be removed independent of each other.
(https://api.jquery.com/on/)

Angular's jqLite however, does not.
(https://docs.angularjs.org/api/ng/function/angular.element)

But if you include JQuery before Angular then JQuery will replace jqLite and you should be able to use namespaces. That's possibly not what you wanted to hear, but I'm not aware of any other way.

like image 39
ivarni Avatar answered Nov 11 '22 21:11

ivarni