Арт*_*щев 14 javascript web-component custom-element es6-proxy es6-class
class A extends HTMLElement {
constructor() {
super()
return new Proxy(this, {})
}
}
window.customElements.define('a-element', A)Run Code Online (Sandbox Code Playgroud)
<a-element></a-element>Run Code Online (Sandbox Code Playgroud)
我如何代理自定义元素?
当我尝试它:
Uncaught InvalidStateError: custom element constructors must call super() first and must not return a different object.
您可以Proxify 类或自定义元素的实例.
给定以下自定义元素定义:
class A extends HTMLElement {
constructor() {
super()
}
connectedCallback() {
this.innerHTML = 'Hello'
}
}
customElements.define( 'a-element', A )
Run Code Online (Sandbox Code Playgroud)
自定义元素实例的代理
从实例引用创建代理(此处:) ae:
<a-element id="ae"></a-element>
<script>
var b1 = new Proxy( ae, {
get ( target, value ) { return target[value] }
} )
console.log( b1.innerHTML ) // => "Hello"
</script>
Run Code Online (Sandbox Code Playgroud)
自定义元素类的代理
定义construct陷阱以捕获new运算符:
<script>
var B = new Proxy( A, {
construct() { return new A }
} )
var b2 = new B
document.body.appendChild( b2 )
console.log( b2.innerHTML ) // => "Hello"
</script>
Run Code Online (Sandbox Code Playgroud)
从类Proxy获取自定义元素实例代理
如果要实例化自定义元素并直接获取一个代理对象,可以将上述两种解决方案结合起来.
以下示例显示如何获取<a-element>将在控制台中登录每个属性访问权限的元素的代理.construct()类Proxy中定义的陷阱返回自身为实例化自定义元素的代理.
class A extends HTMLElement {
constructor() {
super()
}
connectedCallback() {
this.innerHTML = 'Hello'
}
}
customElements.define( 'a-element', A )
var P = new Proxy( A, {
construct () {
return new Proxy ( new A, {
get ( target, value ) {
if ( value == 'element' )
return target
console.info( `proxy: property ${value} for <${target.localName}> is "${target[value]}"` )
return target[value]
}
} )
}
} )
var p = new P
document.body.appendChild( p.element )
console.log( p.innerHTML )Run Code Online (Sandbox Code Playgroud)