1 回答

TA貢獻(xiàn)1864條經(jīng)驗 獲得超6個贊
我最終所做的是將所有成員變量值移動到一個私有對象,并在自定義元素掛載到DOM上后立即為每個對象動態(tài)定義一個 getter/setter,如下所示...
//
class State extends HTMLElement {
protected _data: object = {}
public connectedCallback() {
// Loop over member vars
Object.getOwnPropertyNames(this).forEach(sPropertyKey => {
// Ignore private
if(sPropertyKey.startsWith('_')) {
return;
}
// Copy member var to data object
Reflect.set(this._data, sPropertyKey, Reflect.get(this, sPropertyKey));
// Remove member var
Reflect.deleteProperty(this, sPropertyKey);
// Define getter/setter to access data object
Object.defineProperty(this, sPropertyKey, {
set: function(mValue: any) {
console.log(`setting ${sPropertyKey}`);
Reflect.set(this._data, sPropertyKey, mValue);
},
get: function() {
return this._data[sPropertyKey];
}
});
});
}
}
//
class SubState extends State {
public foobar = 'foobar_val';
public flipflop = 'flipflop_val';
public SubStateMethod() { }
}
//
window.customElements.define('sub-state', SubState);
//
const oState = document.querySelector('sub-state') as SubState;
oState.foobar = 'foobar_new_val';
這樣,我仍然可以像往常一樣獲取/設(shè)置對象的值,typescript很高興成員變量存在,并且我可以在訪問成員時觸發(fā)自定義事件 - 同時允許自定義元素存在于DOM就緒的標(biāo)記中。
添加回答
舉報