Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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.

Thanks

1 Answer

0 votes
by (106k points)
edited by

To unsubscribe to a broadcast event in angularJS and to remove function registered via $on you need to store the returned function and call it to unsubscribe from the event.

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

Looking for Angularjs material from basics! Refer to this video on Angularjs provided by Intellipaat:

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; 

 }; 

},

Related questions

+1 vote
1 answer
0 votes
1 answer
asked Aug 29, 2019 in Web Technology by Sammy (47.6k points)

Browse Categories

...