在我的应用程序中,我使用带有窗口调整大小事件监听器的自定义指令:
link: function(scope, elem, attrs) {
angular.element($window).bind('resize', function() {
// viewId is a unique reference to the view in which the directive lives
console.log(scope.viewId);
});
}
该指令在我的每个 View 中插入 1 次或多次。
令我困惑的是为什么该函数不仅针对事件 View 执行,而且还针对非事件 View 执行。一旦我访问了多个 View ,就会发生这种情况。
更让我困惑的是,为什么在我多次访问同一个 View 后,该函数会从同一个 View 多次调用。
在我看来,旧的指令作用域没有被破坏,而是保持事件状态,并且在旧的作用域之上创建了一个新的作用域。
我可以采取什么措施来防止这种行为?
<小时/>下面是基于 Renan Lopes Ferreira 提供的答案的工作解决方案的代码片段(我使用 LoDash _.debounce 来防止函数被过于频繁地调用):
windowResize = _.debounce(function () {
// My logic
$scope.$apply();
}, 150);
// Attach debounced function to the window.resize event listener
angular.element($window).on('resize', windowResize);
// Remove the function when the directive is destroyed
$scope.$on('$destroy', function () {
angular.element($window).off('resize', windowResize);
});
最佳答案
当您的指令被销毁时,您需要删除监听器。像这样的东西:
angular.element($window).on('resize', resize);
scope.$on('$destroy', function () {
angular.element($window).off('resize', resize);
});
function resize(){
...
}
关于javascript - 事件监听器从同一指令多次触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34288157/