我使用 Ractive 通过 magic: true
参数显示来自不断变化的数组(从 PouchDB 接收)的数据。在 0.9.x 版本中此参数不再可用之前,该功能一直运行良好。
因此,建议每次数组更改时都使用ractive.update()
。我面临的问题看起来很简单,但我相当缺乏经验:
为了跟踪更改,我大致执行以下操作(取自 PouchDB 脚本):
fetchInitialDocs().then(renderDocsSomehow).then(reactToChanges).catch(console.log.bind(console));
function renderDocsSomehow() {
let myRactive = new Ractive({
el: '#myDiv',
template: 'my Template',
//magic: true,
data:{
doc1: docs
},
components: {myComponents},
computed: {computedValues}
});
}
function reactToChanges() {
//here my changes appear
onUpdatedOrInserted(change.doc);
myRactive.update() // <- I cannot use update here because "myRactive" is not known at this point.
}
我还尝试在renderDocsSomehow()
函数中设置一个观察者
ractive.observe('doc1', function(newValue, oldValue, keypath) {
ractive.update()
});
但这并没有达到目的。
那么我如何通知 Ractive 我的数据已更改并且需要自行更新?
最佳答案
如果 reactToChanges
只是一个为 myRactive
设置“监听器”的函数,并且从未在其他地方调用,那么您可以将其代码放在 oninit
。这样,您就可以访问该实例。
function renderDocsSomehow() {
let myRactive = new Ractive({
el: '#myDiv',
template: 'my Template',
//magic: true,
data:{
doc1: docs
},
components: {myComponents},
computed: {computedValues},
oninit(){
//here my changes appear
onUpdatedOrInserted(change.doc);
this.update()
}
});
}
关于javascript - 当数组更改时更新 ractive.js,没有 'magic: true',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50397724/