鉴于:
<template name="child">
<button class=".child.button">Click Me</button>
</template>
<template name="parent">
{{#each children}}
{{> child }}
{{/each}}
</template>
我希望能够将事件链接到可以访问父对象的子模板中的按钮。
可能的解决方案:
我可以将父级存储在 dom 中并执行以下操作:
Template.child.events({
'click .child.button': function (event, template) {
console.log('In this context \'this\' is the CHILD');
// I want the parent object
// I could pull a ref from the Dom? Seems messy.
var parentId = $(event.currentTarget).closest('.parentClass').data('id');
// Do something for this child using parent here
return false;
}
});
或者,我可以将父级保存在会话变量中并从那里拉出:
Router.map(function() {
this.route('parent', {
path: '/parents/:_id',
data: function () {
// Get the current parent and put it into the session
var thisparent = Parents.findOne(this.params._id);
Session.set('currentParent', thisparent);
return {
parent: thisparent
};
}
});
});
接着:
Template.child.events({
'click .child.button': function (event, template) {
console('the parent is: ', Session.get('currentProject'));
return false;
}
});
但理想情况下,我更喜欢更清洁的解决方案,感觉这应该是可能的。