【问题标题】:How can I observe attributes in custom elements using CoffeeScript?如何使用 CoffeeScript 观察自定义元素中的属性?
【发布时间】:2019-06-28 17:14:54
【问题描述】:

我正在尝试观察自定义元素属性的变化。不幸的是,我能找到的所有自定义元素的文档(几乎没有)都是用 JS 编写的,我不知道如何将其中的一些代码转换为 CoffeeScript。

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}`;
        }
    }
}

到目前为止,我已经写了这个:

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

但我不知道如何在 CoffeeScript 中编写“getobservedAttributes”方法。有人可以帮我吗? :)

谢谢

【问题讨论】:

    标签: coffeescript custom-element


    【解决方案1】:
    class HelloElement extends HTMLElement
        @observedAttributes: ['name']
    
        attributeChangedCallback: (attr, oldValue, newValue) ->
            console.log("attr #{ attr } changed from #{ oldValue } to #{ newValue }")
    

    感谢 Reddit 用户 _redka (https://www.reddit.com/user/_redka/) 提供此解决方案!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-20
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      相关资源
      最近更新 更多