Angular event only meant to trigger once triggering multiple times

I have an event that I only want to handle a single time. Based on my understanding of this and this blog, having the following style should ensure this behavior:

var unbind = $scope.$on(event, function(){
    //do stuff
    unbind();
}

But when I put a breakpoint in this code I can see its being called multiple times.

How can I ensure that the code is run once and only once?

Upvotes: 0

Views: 1081

Answers (1)

Due to the asynchronous nature of events, the unbind() call needs to be called first, not last, to prevent multiple simultaneous events.

var unbind = $scope.$on(event, function(){
    unbind();//first, not last
    //do stuff
}

Upvotes: 1

Related Questions