2

鉴于:

<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;
  }
});

但理想情况下,我更喜欢更清洁的解决方案,感觉这应该是可能的。

4

1 回答 1

3

到目前为止,您无法使用 API 从事件中访问父数据。

从一个助手中,您可以使用:

UI._parentData()

但是在一个事件中,这将返回 null。

最好的解决方案是使用一些模板魔法

{{#each children}}
    {{#with context=this parent=..}}
        {{> child this}}
    {{/with}}
{{/each}}

允许:

Template.child.events({
  'click .child.button': function (event, template) {
    console('the parent context is: ', this.parent);
    console('the current context is: ', this.context);
    return false;
  }
});
于 2014-07-02T11:38:53.727 回答