流星,更新时的反应式数组渲染问题

Meteor, reactive array rendering issues on update

本文关键字:数组 问题 反应式 更新 流星      更新时间:2023-09-26

我有一个嵌套模板,使用ReactiveDict来存储数据,这是一个包含变量(颜色,类型...)和子节点数组的对象。

我在刷新时遇到问题:数组以反应方式显示,但是当我更新数组时,它无法正确呈现。

简而言之(清理代码):

<body>
{{#with data}}
   {{>nested}}
{{/with}}
</body>
<template name="nested">
<div>{{color}}<div>
<div class="ui dropdown">
<!-- drop down stuff goes here-->
</div>
{{#if children}}
{{#each children}}
   {{>nested scope=this}}
{{/each}}
{{/if}}
</template>
Template.body.helpers({
"data": { color: "blue", 
children: [{color: "green", children: [{color: "teal"}]},
 {color:"red", children:[{color: "cyan"}],{color: "magenta"}]]}}
})
Template.nested.onCreated(function(){
        this.scope          = new ReactiveDict();
        this.scope.set('scope', this.data.scope);
})
Template.nested.helpers({
"color": function () { Template.instance().scope.get('scope').color;},
"children": function () {
        return Template.instance().scope.get('scope').children;
    }
})
Template.nested.events({
"click .ui.dropdown > .menu > .item": function(e, t) {
    e.preventDefault();
    e.stopPropagation();
    var data = t.scope.get('scope');
    //do processing stuff here...
    updatedArray = myFunction();
    data['children'] = updatedArray;
    t.scope.set('scope', data);
}
})

所以正在发生的事情是,在更新时,已经存在的元素不会更新,如果添加了元素,它们就会显示出来。如果删除了元素,它们将被删除,但变量中的数据(此处为颜色)不会更新。

为了使它到目前为止正常工作,我必须执行以下操作:

Template.nested.events({
    "click .ui.dropdown > .menu > .item": function(e, t) {
        e.preventDefault();
        e.stopPropagation();
        var data = t.scope.get('scope');
        //do processing stuff here...
        updatedArray = myFunction();
        delete data.children;
        t.scope.set('scope', data);
        Meteor.setTimeout(function() {
             data['children'] = updatedArray;
            t.scope.set('scope', data);
         },10);
    }
    })

这有效,但这是一个完全的黑客,迫使数组一无所有,然后在短暂超时后刷新。

我应该如何以正确的方式做到这一点?PS:我尝试在ReactiveDict上使用allDeps.changed(),并尝试强制重新渲染,但它在渲染循环中,因此它不会渲染视图两次。似乎无法理解为什么数组元素没有更新。我知道在使用集合时,MiniMongo会检查对象的_id以查看它们是否更改,但是我的对象中没有_id。我也试图添加一个,但没有太多运气

好吧,

我想我在弄清楚之前问过..."_id"的事情起到了作用。我以前试过,但我实际上对相同的元素使用相同的_id,所以它们似乎没有改变(嘟!

因此,通过在生成的对象中添加{ "_id": Meteor.uuid() },更新工作正常。