猿问

如何取消订阅angularJS中的广播事件。如何删除通过$ on注册的功能

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


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

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


AngularJS中有什么方法可以取消注册特定的侦听器?诸如$ on之类的方法可以注销该事件,可能是$ off。因此,基于业务逻辑,我可以说


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

并且当有人广播“ onViewUpdated”事件时,该函数将停止调用。


谢谢


编辑:我想注销另一个功能的侦听器。不是我注册的功能。


精慕HU
浏览 945回答 3
3回答

陪伴而非守候

查看大多数答复,它们似乎过于复杂。Angular具有内置的注销机制。使用以下命令返回$on的注销功能:// Register and get a handle to the listenervar listener = $scope.$on('someMessage', function () {    $log.log("Message received");});// Unregister$scope.$on('$destroy', function () {    $log.log("Unregistering listener");    listener();});

大话西游666

您需要存储返回的函数并调用它以取消订阅该事件。var deregisterListener = $scope.$on("onViewUpdated", callMe);deregisterListener (); // this will deregister that listener至少在1.0.4中可以在源代码中找到它:)。由于简短,我将发布完整的代码/**  * @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;    };},

慕容3067478

正确的方法是在@LiviuT的答案!您总是可以扩展Angular的范围,以允许您删除此类侦听器,如下所示://A little hack to add an $off() method to $scopes.(function () {&nbsp; var injector = angular.injector(['ng']),&nbsp; &nbsp; &nbsp; rootScope = injector.get('$rootScope');&nbsp; &nbsp; &nbsp; rootScope.constructor.prototype.$off = function(eventName, fn) {&nbsp; &nbsp; &nbsp; &nbsp; if(this.$$listeners) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var eventArr = this.$$listeners[eventName];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(eventArr) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(var i = 0; i < eventArr.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(eventArr[i] === fn) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; eventArr.splice(i, 1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }}());这是它的工作方式:&nbsp; function myEvent() {&nbsp; &nbsp; alert('test');&nbsp; }&nbsp; $scope.$on('test', myEvent);&nbsp; $scope.$broadcast('test');&nbsp; $scope.$off('test', myEvent);&nbsp; $scope.$broadcast('test');
随时随地看视频慕课网APP

相关分类

AngularJS
我要回答