有什么方法可以侦听纯Javascript中实例变量的更改,然后在更改时调用方法?
我想从此类开始,使用这种模式更新表:
class TableUpdater {
tabledata;
async setData(editedRow) {
const response = await fetch('http://example.com/api', {
method : 'post'
, headers : {
"Content-Type" : "application/json"
}
, body : JSON.stringify(editedRow)
});
const updatedData = await response.json();
this.tabledata = updatedData;
}
async updateTable(arg1) {
// can do the below, but it would be nice to decouple setData() from updateTable()
// await this.setData(arg1);
// table creation logic
}
}
const tableUpdater = new TableUpdater();
答案 0 :(得分:0)
class TableUpdater {
tabledata;
listeners = [];
onSetData(listener) {
this.listeners.push(listener)
}
async setData(editedRow) {
setTimeout((newData) => {
for (let i = 0; i < this.listeners.length; i++) {
this.listeners[i](newData)
}
this.tableData = newData
}, 1000, [{
foo: 'bar'
}])
}
}
const tableUpdater = new TableUpdater();
tableUpdater.onSetData(console.log)
tableUpdater.setData();