我是流星/烈焰的新手,但这就是我公司所使用的。
我正在努力了解Blaze如何根据ReactiveDict
决定渲染什么内容>
反应变量<template name="parent"> {{#each child in getChildren}} {{> childTemplate (childArgs child)}} {{/each}} </template>
家长Javascript
模板通过仅检索getChildren
的ReactiveDict
帮助器呈现子模板。
模板)// Child data object const child = () => ({ id: uuid.v4(), data: "" }); // Create a reactive dictionary Template.parent.onCreated(function() { this.state = new ReactiveDict(); this.state.setDefault({ children: [child()] }); });
子模板参数(来自parent// Return the children from the reactive dictionary Template.parent.helpers({ getChildren() { return Template.instance().state.get('children'); } });
父模板为子模板提供了一些用于设置默认值和回调的数据。每个函数都使用childArgs
函数实例化,该函数使用子级的id
设置正确的数据和回调。单击add
按钮时,它将在children
中的ReactiveDict
数组中添加一个子项。单击delete
按钮时,它将从children
的ReactiveDict
数组中删除子级。
Template.parent.helpers({ // Set the children arguments: default values and callbacks childArgs(child) { const instance = Template.instance(); const children = instance.state.get('children'); return { id: child.id, // Default values data: child.data, // Just adding a child to the reactive variable using callback onAddClick() { const newChildren = [...children, newChild]; Template.instance().state.set('children', newChildren); }, // Just deleting the child in the reactive variable in the callback onDeleteClick(childId) { const childIndex = children.findIndex(child => child.id === childId); children.splice(childIndex, 1); Template.instance().state.set('children', children); } } } })
儿童
模板显示来自父级和2个按钮的数据,add
和delete
。
<template name="child"> <div>{{data}}</div> <button class="add_row" type="button">add</button> <button class="delete_row" type="button">delete</button> </template>
子javascript(事件)
这里调用的两个函数是从parent模板作为参数传递的回调。
// The two functions are callbacks passed as parameters to the child template Template.child.events({ 'click .add_row'(event, templateInstance) { templateInstance.data.onAddClick(); }, 'click .delete_row'(event, templateInstance) { templateInstance.data.onDeleteClick(templateInstance.data.id); },
问题
我的问题是,当我删除一个孩子时(使用回调函数将ReactiveDict
设置为onAddClick()
函数一样,我的数据无法正确呈现。
示例:
我添加这样的行。child 1 | data 1 child 2 | data 2 child 3 | data 3
[删除
child 2
时,我得到了:
child 1 | data 1 child 3 | data 2
我想要这个:
child 1 | data 1 child 3 | data 3
我正在使用
child
功能中来自childArgs
的数据初始化Template.child.onRendered()
。
getChildren()
中的child
时调用ReactiveDict
函数,并且变量中有正确的数据(children
中的ReactiveDict
)。 onRendered()
(孩子的onCreated()
函数也不被调用)。这表示child模板显示的数据错误。我可能误会了一些东西。您能帮我吗?
我是Meteor / Blaze的新手,但这就是我公司所使用的。我正在努力了解Blaze如何决定根据ReactiveDict Parent父HTML模板
我不确定从哪里开始,但有很多错误,我想在此处提供运行中的解决方案并附带注释。
[首先,each
函数应正确传递ID而不是整个子代,否则find
将导致错误: