How to unsubscribe ...
Notifications
Clear all

How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on

RSS

(@anamika)
Noble Member
Joined: 1 year ago
Posts: 1381
12/05/2021 12:32 pm

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

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

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

Is there any method in AngularJS to unregister a particular listener? A method like $on that unregister this event, maybe $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.


Quote
(@ganesh)
Noble Member
Joined: 1 year ago
Posts: 1362
12/05/2021 12:33 pm

退订to a broadcast event in angularJS and to remove function registeredvia$on you need to store the returned function and call it to unsubscribe from the event.

var deregisterListener = $scope.$on("onViewUpdated", callMe); deregisterListener ();

The code is as follows:-

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

};

},


ReplyQuote
Share:
Baidu