Vanilla Web Component custom event attributes and properties(Vanilla Web 组件自定义事件属性和属性)
问题描述
在没有任何框架的情况下使用 Web 组件,实现自定义事件的正确方法是什么?例如,假设我有一个自定义元素 x-pop-out
有一个自定义事件 pop
我希望以下所有操作都能正常工作:
Using Web Components without any framework, what is the proper way to implement a custom event? For example, say I have a custom element x-pop-out
that has a custom event of pop
I would want all of the following to work:
<x-pop-out onpop="someGlobal.doSomething()"/>
var el = document.getElementsByTagName('x-pop-out')[0];
el.onpop = ()=> someGlobal.doSomething();
//or
el.addEventListener('pop', ()=> someGlobal.doSomething());
最后一个我知道该怎么做,但是我需要自定义实现属性和每个 getter/setter 吗?另外,eval()
是从属性执行字符串的适当方式吗?
The last one I get how to do, but do I need to custom implement the attribute and a getter / setter for each? Also, is eval()
the appropriate way to execute the string from the attribute?
推荐答案
事件监听器 解决方案(第三种)是最简单的,因为您不必定义任何特殊的东西来捕获事件.
The event listener solution (the third one) is the easiest because you don't have to define anything special to catch the event.
事件处理程序解决方案需要制作一个eval()
(第一个,来自属性)或显式调用函数(第二个).
The event handler solutions need to make an eval()
(first one, from attribute) or to call the fonction explicitely (second one).
如果你不能使用 eval
你可以改为解析属性字符串.
If you can't use eval
you can instead parse the attribute string.
customElements.define( 'x-pop-out', class extends HTMLElement {
connectedCallback() {
this.innerHTML = `<button id="Btn">pop</button>`
this.querySelector( 'button' ).onclick = () => {
this.dispatchEvent( new CustomEvent( 'pop' ) )
if ( this.onpop )
this.onpop()
else
eval( this.getAttribute( 'onpop' ) )
}
}
} )
XPO.addEventListener( 'pop', () => console.info( 'pop' ) )
<x-pop-out id=XPO onpop="console.log( 'onpop attribute' )"></x-pop-out>
<hr>
<button onclick="XPO.onpop = () => console.log( 'onpop override' )">redefine onpop</button>
这篇关于Vanilla Web 组件自定义事件属性和属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Vanilla Web 组件自定义事件属性和属性


基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01