1
class ProfileCollaboration {

    constructor() { 
        document.addEventListener('profileEvent', this.profileEvent)
    }

    profileEvent(event) {
        let profileEvent = event.detail
    
        if (profileEvent.name !== 'profileEditing') {
            return
        }
    
        if (profileEvent.editing === true) {
            console.log(this)
            this.enableEditingMode()
        } else {
            this.disableEditingMode()
        }
    }

    enableEditingMod() {
        console.log('enabled');
    }

    disableEditingMode() {
        console.log('disabled');
    }

}

Console log says: this.enableEditingMode is not a function

Which is correct because this is now the context of the addEventListener.

How can I listen for events inside a js class?

2
  • Is there a profileEvent event? Commented Aug 26, 2021 at 17:10
  • 1
    Um, do you people realize you can fire any custom events? :) Commented Aug 26, 2021 at 17:13

1 Answer 1

3

event listener callbacks are by default binded to element.

If you want it work, you should attach it like this:

document.addEventListener('profileEvent', this.profileEvent.bind(this));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, I didn't even now bind existed developer.mozilla.org/de/docs/Web/JavaScript/Reference/… this is awesome!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.