gpt4 book ai didi

AngularJS - 从特定指令取消绑定(bind)事件的 $window

转载 作者:行者123 更新时间:2023-12-03 15:15:48 25 4
gpt4 key购买 nike

在我的一个指令中,我使用 angular.element($window).bind('scroll') .当指令被销毁时,我想unbind它。通常,我会这样做:

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

但是如果另一个指令也绑定(bind)到 scroll 怎么办? $window 的事件,并且该事件仍然需要存在。如果我使用 unbind上面,其他指令的绑定(bind)也被消除了。

我有哪些选择?

最佳答案

将相同的函数引用传递给 unbind/off,就像传递给 bind/on 以取消绑定(bind)该特定处理程序:

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 中,函数 bindunbind已弃用。但是,您仍然可以将它们与 jQuery 和 jqLit​​e 一起使用,因为它们只需调用 onoff在幕后。

关于AngularJS - 从特定指令取消绑定(bind)事件的 $window,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25440775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com