如何取消订阅 angularJS 中的广播事件.如何删除通过 $on 注册的函数 [英] How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on

查看:26
本文介绍了如何取消订阅 angularJS 中的广播事件.如何删除通过 $on 注册的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已使用 $on 函数将我的侦听器注册到 $broadcast 事件

$scope.$on("onViewUpdated", this.callMe);

并且我想根据特定的业务规则取消注册此侦听器.但我的问题是,一旦注册,我就无法取消注册.

AngularJS 中是否有任何方法可以取消注册特定的侦听器?像 $on 这样取消注册此事件的方法可能是 $off.所以基于业务逻辑我可以说

 $scope.$off("onViewUpdated", this.callMe);

当有人广播onViewUpdated"事件时,此函数将停止调用.

谢谢

编辑:我想从另一个函数取消注册监听器.不是我注册的函数.

解决方案

您需要存储返回的函数并调用它来取消订阅事件.

var deregisterListener = $scope.$on("onViewUpdated", callMe);注销监听器();//这将取消注册该侦听器

这可以在源代码中找到 :) 至少在 1.0.4 中.我会发布完整的代码,因为它很短

/*** @param {string} name 要监听的事件名称.* @param {function(event)} listener 事件发生时调用的函数.* @returns {function()} 返回此侦听器的注销函数.*/$on: 函数(名称,监听器){var namedListeners = this.$$listeners[name];如果 (!namedListeners) {this.$$listeners[name] = namedListeners = [];}namedListeners.push(listener);返回函数(){namedListeners[indexOf(namedListeners, listener)] = null;};},

另请参阅文档.>

I have registered my listener to a $broadcast event using $on function

$scope.$on("onViewUpdated", this.callMe);

and I want to un-register this listener based on a particular business rule. But my problem is that once it is registered I am not able to un-register it.

Is there any method in AngularJS to un-register a particular listener? A method like $on that un-register this event, may be $off. So that based on the business logic i can say

 $scope.$off("onViewUpdated", this.callMe);

and this function stop being called when somebody broadcast "onViewUpdated" event.

Thanks

EDIT: I want to de-register the listener from another function. Not the function where i register it.

解决方案

You need to store the returned function and call it to unsubscribe from the event.

var deregisterListener = $scope.$on("onViewUpdated", callMe);
deregisterListener (); // this will deregister that listener

This is found in the source code :) at least in 1.0.4. I'll just post the full code since it's short

/**
  * @param {string} name Event name to listen on.
  * @param {function(event)} listener Function to call when the event is emitted.
  * @returns {function()} Returns a deregistration function for this listener.
  */
$on: function(name, listener) {
    var namedListeners = this.$$listeners[name];
    if (!namedListeners) {
      this.$$listeners[name] = namedListeners = [];
    }
    namedListeners.push(listener);

    return function() {
      namedListeners[indexOf(namedListeners, listener)] = null;
    };
},

Also, see the docs.

这篇关于如何取消订阅 angularJS 中的广播事件.如何删除通过 $on 注册的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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