你需要使用一个ReactiveVar https://atmospherejs.com/meteor/reactive-var存储当前单击的项目。
首先你需要运行meteor add reactive-var
,因为它不是标准 Meteor Web 应用程序中默认添加的包。
JS:
Template.adminManageCategories.created=function(){
// instantiate the reactive-var in the created callback
// we store it as a property of the template instance
this.currentItemId=new ReactiveVar(null);
};
Template.adminManageCategories.helpers({
// this helper reactively returns the currently clicked item
currentItem:function(){
// retrieve the reactive-var from the template instance...
var currentItemId=Template.instance().currentItemId.get();
// ...to fetch the correct collection document
return Items.findOne(currentItemId);
}
});
Template.adminManageCategories.events({
"click .clickme": function(event,template) {
event.preventDefault();
// assign the correct item id to the reactive-var attached to this template instance
template.currentItemId.set(this._id);
}
});
HTML:
<template name="adminManageCategories">
{{#each category}}
<div class="clickme">{{title}}</div>
{{/each}}
<p>Current item title is : {{currentItem.title}}</p>
{{! pass the currentItem as a parameter to your child template this will be
accessible as {{item}} in the HTML and "this.item" in JS helpers or
"this.data.item" in created/rendered/destroyed callbacks}}
{{> adminUpdateCategory item=currentItem}}
</template>
EDIT:
当我初始化reactive-var时created
回调,我将其设置为 null,这意味着在单击一项之前,助手也会返回 null,当您尝试访问时this.item._id
in the adminUpdateCategory
这会失败。
解决此问题的最简单方法可能是不将变量初始化为 null,而是初始化为集合中的第一项。
Template.adminManageCategories.created=function(){
var firstItem=Items.findOne({},{
sort:{
sortedField:1
}
});
this.currentItemId=new ReactiveVar(firstItem && firstItem._id);
};
仍然可能存在集合中有 0 个项目的情况,因此您可能最终不得不防止 JS 中存在该项目。
Template.adminUpdateCategory.helpers({
itemProperty:function(){
return this.item && this.item.property;
}
});