2

I am using $broadcast and $emit in my angularjs application. Here is the code i am registering $emit function :

this.scope.$emit('changeTime', {
  currentTime: this.currentTime
});

In another controller i am listening this emit function for returning is object like :

this.scope.$on('changeTime', (event, args) => {
  console.log(args.currentTime);
});

Here is all working fine. But this listener is calling in my different function which is called according to different condition :

 this.functionone(){
      this.scope.$on('changeTime', (event, args) => {
        console.log(args.currentTime);
      });
    }

    this.functiontwo(){
      this.scope.$on('changeTime', (event, args) => {
        console.log(args.currentTime);
      });
    }

When i call first function current time printed in console. When my condition is changes and calling another function functiontwo() in that time i can also see the functionone console value.

Meaning changetime listener calling two times when second function get call after one.

So how can i unregister this earlier called changetime. So second time its not come.

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
Gitesh Purbia
  • 1,094
  • 1
  • 12
  • 26
  • Possible duplicate of [How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on](http://stackoverflow.com/questions/14898296/how-to-unsubscribe-to-a-broadcast-event-in-angularjs-how-to-remove-function-reg) – Kursad Gulseven Mar 09 '17 at 07:42

1 Answers1

3

By design listeners/$watch function returns de-registration function. So you could unregister the events by calling dereigster function directly(if they are exists).

this.functionone = function(){
  this.deregisterEvents();
  this.eventOneChangeTime = this.scope.$on('changeTime', (event, args) => {
    console.log(args.currentTime);
  });
}

this.functiontwo = function(){
  this.deregisterEvents();
  this.eventTwoChangeTime = this.scope.$on('changeTime', (event, args) => {
    console.log(args.currentTime);
  });
}

deregisterEvents(){
    //unregistering events.
    if(this.eventOneChangeTime) this.eventOneChangeTime();
    if(this.eventTwoChangeTime) this.eventTwoChangeTime();
}
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299