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

または、親をセッション var に保持し、そこからプルすることもできます。

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 に答える