自定义元素,自定义事件处理程序属性

时间:2020-02-02 01:54:05

标签: custom-element custom-events

内置在浏览器元素中的事件属性可以执行如下所述的任意javascript

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers

有没有办法创建具有类似 custom事件处理程序属性的自定义元素,并且有这样做的标准模式吗? eventType} =“ {some code}”在范围内使用正确的值执行,并且此绑定设置正确。

<some-custom-element oncustomevent="alert('worked')" />

1 个答案:

答案 0 :(得分:1)

第一个问题是:您是否真的要允许从字符串执行代码?因为它需要eval()

使用eval()并没有错,在您理解其含义之后

触发动态(字符串)代码:

  • 来自“自定义元素”属性onevent
  • 来自自定义元素设置器onevent
  • 来自自定义事件onevent的详细信息(请参阅connectedCallback

  function triggerEvent(name, code = "console.warn('No code parameter')") {
    console.log(name, this);
    if (this === window) console.warn('no element scope');
    try {
      if (typeof code === "string") eval(code);
      else console.warn("code is not a string")
    } catch (e) { console.error(e) }
  }
  customElements.define("my-element", class extends HTMLElement {
    static get observedAttributes() {
      return ['onevent'];
    }
    constructor() {
      super();
      this.onclick = () => triggerEvent.call(this, "element Click", "console.log('from element click')");
    }
    connectedCallback() {
      document.addEventListener("onevent", evt => {
        triggerEvent.call(this, "EventListener", evt.detail);
      })
    }
    attributeChangedCallback(name, oldValue, newValue) {
      if (name === "onevent") {
        triggerEvent.call(this, "attributeChangedCallback", newValue);
      }
    }
    set onevent(newValue) {
      triggerEvent.call(this, "setter", newValue);
    }
  });

  setTimeout(() => document.dispatchEvent(new CustomEvent("onevent", {
      detail: "console.log('from dispatchEvent detail')"
    })), 2000); //execute after elements listen
<my-element onevent="console.log('from element attribute')">click my-element</my-element>
<button onclick="document.querySelector('my-element').onevent='console.log(&quot;from button&quot;)'"
>Call setter</button>

JSFiddle游乐场位于https://jsfiddle.net/CustomElementsExamples/s9jm72nf/