我可能是错的,但看起来您想要做的是在自定义元素的value
属性发生更改时触发更改事件。这就是你可以做到的方式。
定义组件
xtag.register('my-element', {
accessors: {
value: {
attribute: {},
get: function () {
return this._value;
},
set: function (v) {
if (v === this._value) return; // unchanged
var change = { from: this._value, to: v }; // optional
this._value = v; // set new value
xtag.fireEvent(this, 'change', { // event
detail: change,
bubbles: true,
cancelable: true
});
}
}
}
});
HTML
<my-element value="2"></my-element>
试试看
var el = document.querySelector('my-element');
// add event listener
el.addEventListener('change', function (e) {
console.log('value changed from %s to %s', e.detail.from, e.detail.to);
});
// change the value
el.value = 4;
// this will cause the 'change' event to fire
// the listener will output this to the console:
// "value changed from 2 to 4"
因为我们已经将change
事件的bubbles
选项设置为true
,所以我们也可以使用事件委托。
xtag.addEvent(document.body, 'change:delegate(my-element)', function (e) {
console.log('Value of <my-element> somewhere in <body> changed');
});