1

I have a non AngularJS snippet that is communicating with my AngularJS modules via custom events. Each of these AngularJS modules represents a different route. When I am leaving each route $onDestroy is triggered but does not remove the event listener. What am I missing to un-register my custom event?

Non AngularJS HTML Snippet

<script>
function sendEvent() {
    const payload = getPayload();
    const event = new CustomEvent('myCustomEvent', { payload });
    window.dispatchEvent(event);
}
</script>

<button onclick="sendEvent()">Send Custom Event</button>

AngularJS Component

Class ModuleA {
    $onInit() {
        this.$window.addEventListener('myCustomEvent', this.onCustomEventClick.bind(this));
    }

    $onDestroy() {
        this.$window.removeEventListener('myCustomEvent', this.onCustomEventClick.bind(this), false);
    }
}

Class ModuleB {
    $onInit() {
        this.$window.addEventListener('myCustomEvent', this.onCustomEventClick.bind(this));
    }

    $onDestroy() {
        this.$window.removeEventListener('myCustomEvent', this.onCustomEventClick.bind(this), false);
    }
}

1 Answer 1

2

Every time you call bind it will create a new function and return it instead of modifying the function itself. So the even listeners you provide to addEventListener and removeEventListener are different functions, thus the registered ones are not removed.

To solve it, call bind once in $onInit and keep a reference to the returned function and always use that reference:

Class ModuleB {
    $onInit() {
        this.onCustomEventClick = this.onCustomEventClick.bind(this)
        this.$window.addEventListener('myCustomEvent', this.onCustomEventClick);
    }

    $onDestroy() {
        this.$window.removeEventListener('myCustomEvent', this.onCustomEventClick, false);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.