Search code examples
coffeescriptcustom-element

How can I observe attributes in custom elements using CoffeeScript?


I'm trying to observe changes in a custom element's attributes. Unfortunately all of the documentation I can find for custom elements (which is next to nothing) is written in JS, and I don't know how to convert some of this code into CoffeeScript.

The JS:

class HelloElement extends HTMLElement {
// Monitor the 'name' attribute for changes.

    static get observedAttributes() {return ['name']; }
    // Respond to attribute changes.

    attributeChangedCallback(attr, oldValue, newValue) {
        if (attr == 'name') {
            this.textContent = `Hello, ${newValue}`;
        }
    }
}

So far I have written this:

class HelloElement extends HTMLElement

    #STUCK HERE!
    #I can't figure out how to convert the get observedAttributes() method....

    attributeChangedCallback(attr, oldValue, newValue): ->
        if attr == 'name'
            @textContent = 'Hello, ' + newValue

But I have no idea how to write the "get observedAttributes" method in CoffeeScript. Could someone help me please? :)

Thanks


Solution

  • class HelloElement extends HTMLElement
        @observedAttributes: ['name']
    
        attributeChangedCallback: (attr, oldValue, newValue) ->
            console.log("attr #{ attr } changed from #{ oldValue } to #{ newValue }")
    

    Thanks to Reddit user _redka (https://www.reddit.com/user/_redka/) for this solution!