Warm tip: This article is reproduced from serverfault.com, please click

window.addEventListener in angularjs controller cause to call twice or more

发布于 2020-11-26 11:43:56

I use window.addEventListener in a AngularJs controller to bind event listener, but the problem is that when i go to another state and back to this state, the event listener function called twice and repeats, because of binding event listener multiple times.

This is my controller code:

window.addEventListener("message", receivePosMessage, false);

I want to receivePosMessage invoked after window.postMessage. so i used addEventListener. How can i solve this problem?

UPDATE

I also added window.removeEventListener("message", receivePosMessage, false); before addEventListener but didn't worked!

Questioner
Rasool Ghafari
Viewed
0
Rasool Ghafari 2020-11-29 01:34:07

The problem solved with adding theses below code into controller:

$scope.$on('$destroy', function() {
    window.removeEventListener("message", receivePosMessage, false);
});

This solution was given by dear @cody-mikol.