AngularJS - 特定指令的事件取消绑定$窗口 [英] AngularJS - Unbind $window of an event from specific directive

查看:716
本文介绍了AngularJS - 特定指令的事件取消绑定$窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的指令之一,我用 angular.element($窗口).bind('滚动')。当指令被破坏,然后,我想解除它。通常情况下,我会只是做:

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.

我有哪些选择?

推荐答案

传递相同功能的参考解除绑定/关传递给绑定/上刚刚解除绑定特定的处理程序:

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);

例如:

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

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

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

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

请注意,在jQuery的功能绑定取消绑定是德precated。但是,您仍然可以使用这两个与jQuery和jqLit​​e,因为他们只是叫关闭幕后。

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.

这篇关于AngularJS - 特定指令的事件取消绑定$窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆