Search code examples
javascripteventsstimulusjs

How to intercept a Custom Event when event name contains a dot?


I'm trying to intercept an event from the stimulus-autocomplete library.

When I try to intercept the toggle event, it works fine.

export default class extends Controller {
    //...
    toggle(event) {
        console.log(event);
    }
}

I know try to intercept an event when user selects a new value. I read in documentation:

autocomplete.change fires when the users selects a new value from the autocomplete field. The event detail contains the value and textValue properties of the selected result.

...

toggle fires when the results element is shown or hidden.

The dot is surprising. I checked in the code source of the library. Yes, there is a dot.

 new CustomEvent("autocomplete.change", { 

Ok, so I tried with a dot, but, during compilation, I have a syntax error on the dot.

export default class extends Controller {
    autocomplete.change(event) {                 
        console.log(event);
    }
}

Nothing happen when I tried:

export default class extends Controller {
    change(event) {
        console.log(event);
    }
}

Nothing happen when I tried with quotes. I mean, the log is always empty whatever I do.

export default class extends Controller {
    'autocomplete.change'(event) {
        console.log(event); 
    }
}

How to intercept the custom event autocomplete.change?


Solution

  • I found a solution on Hotwire. I have to add a listener on document.

    export default class extends Controller {
        
        connect() {
            document.addEventListener("autocomplete.change", this.autocomplete.bind(this))
        }
    
        autocomplete(event) {
           console.log(event)
        }