我正在阅读Javascript复合模式,想知道新的web组件是否适合这个模式。在谷歌上搜索后,我发现很少有文章直接讨论这个话题。这两者之间有什么关系?有人能指出这方面的课程或文章吗?
发布于 2019-10-02 18:02:19
将组合模式实现为Web组件有不同的方法。
一种简单的方法是定义一个基类,它将公开一些方法(您的统一接口),然后定义将使用基类的扩展的不同Custom元素。
//Create a base class with unified methods (or props, or display)
class BaseElement extends HTMLElement {
sayYourName() {
console.log( "hello, I'm a " + this.localName )
}
}
//Define differents elements that extends the Base one
class Type1 extends BaseElement {}
customElements.define( 'type-1', Type1 )
class Type2 extends BaseElement {}
customElements.define( 'type-2', Type2 )
//Call the common method against diffrent types of custom elements
var elems = document.querySelectorAll( 'div *' )
elems.forEach( e => e.sayYourName() )<div>
<type-1>Type1</type-1>
<type-2>Type2</type-2>
</div>
https://stackoverflow.com/questions/58196758
复制相似问题