properties - 如果之前定义了属性,则不会触发 WebComponents 属性设置器
问题描述
如果之前定义了属性,则不会触发 WebComponents 属性设置器。如下:
<foo-bar id='ele1'></foo-bar>
<foo-bar id='ele2'></foo-bar>
<script>
ele1.foo = 'hello';
class FooBar extends HTMLElement {
set foo(val) {
console.log(`set ${this.id} to ${val}`);
this._foo = val;
}
get foo() {
return this._foo
}
}
customElements.define('foo-bar', FooBar);
setTimeout(() => {
ele1.foo = 'world';
ele2.foo = 'world';
console.log(`ele1.foo is ${ele1.foo}`);
console.log(`ele2.foo is ${ele2.foo}`);
}, 1000);
</script>
控制台输出(set ele1 to world
不是输出):
set ele2 to world
ele1.foo is world
ele2.foo is world
所以我必须Object.defineProperty
像这样观察这个属性:
<foo-bar id='ele1'></foo-bar>
<foo-bar id='ele2'></foo-bar>
<script>
ele1.foo = 'hello';
class FooBar extends HTMLElement {
constructor() {
super();
this._foo = this.foo;
Object.defineProperty(this, 'foo', {
get: () => this._foo,
set: val => {
console.log(`set ${this.id} to ${val}`);
this._foo = val;
}
})
}
}
customElements.define('foo-bar', FooBar);
setTimeout(() => {
ele1.foo = 'world';
ele2.foo = 'world';
console.log(`ele1.foo is ${ele1.foo}`);
console.log(`ele2.foo is ${ele2.foo}`);
}, 1000);
</script>
解决方案
<foo-bar id='ele1'></foo-bar>
<foo-bar id='ele2'></foo-bar>
<script>
ele1.foo = 'hello';
class FooBar extends HTMLElement {
constructor() {
super();
this._foo = this.foo;
delete this.foo;
}
set foo(val) {
console.log(`set ${this.id} to ${val}`);
this._foo = val;
}
get foo() {
return this._foo
}
}
customElements.define('foo-bar', FooBar);
setTimeout(() => {
ele1.foo = 'world';
ele2.foo = 'world';
console.log(`ele1.foo is ${ele1.foo}`);
console.log(`ele2.foo is ${ele2.foo}`);
}, 1000);
</script>
推荐阅读
- python - Python中的嵌套循环奇数模式
- python - Python:如何在嵌套循环中用下一个替换 tqdm 进度条?
- laravel - 我如何保持当前使用 Laravel 登录
- python - PySPC(或 Python 的任何其他统计过程控制库)
- python - 管道没有正确使用自定义模型的标准缩放器
- python - 确保其他人可以运行我的 python 程序的可靠方法
- r - 在 R 中围绕统计测试编写函数
- java - 不推荐在没有设置文件的情况下执行 Gradle:如何编写设置文件以及保存位置
- r - 从删除截距的混合模型生成预测值
- reactjs - 拖放 Formik 组件上的状态未更新