内置在浏览器元素中的事件属性可以执行如下所述的任意javascript
有没有办法创建具有类似 custom事件处理程序属性的自定义元素,并且有这样做的标准模式吗? eventType} =“ {some code}”在范围内使用正确的值执行,并且此绑定设置正确。
<some-custom-element oncustomevent="alert('worked')" />
答案 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("from button")'"
>Call setter</button>
JSFiddle游乐场位于https://jsfiddle.net/CustomElementsExamples/s9jm72nf/