【问题标题】:Meteor: how to access parent properties within nested templates?Meteor:如何访问嵌套模板中的父属性?
【发布时间】:2012-10-17 00:19:29
【问题描述】:

我开始使用 Meteor,并调整 todo example 以包含嵌套标签组。我有以下 HTML,它输出每个标签组的每个名称,以及每个组中的标签列表:

  <template name="tag_filter">
    {{#each tag_types }}
      {{ tag_name }}
      {{#each values }}
        <div data-taggroup="{{ ../tag_name }}">
        {{ name }} ({{ count }})
        </div>
      {{/each}} 
    {{/each}}
</template>

我的问题是:如何调整事件处理程序以点击标签以访问父组的tag_name 的值? (即来自外部每个循环的数据)。

目前我有下面的代码,但this 对象只能让我访问name 和count。

Template.tag_filter.events({
  'mousedown .tag': function () {
    console.log('tag mousedown', this);
    // How do I get the value of tag_name?
  }
});

如您所见,我使用Handlebars parent paths 添加了一个包含名称的data-taggroup 属性,但我不确定如何从事件处理程序中访问它。

我认为this question 是相关的,但我不理解 OP 的解决方案(部分原因是我没有使用 Coffeescript)。还有一个相关的closed Meteor issue。

【问题讨论】:

    标签: meteor


    【解决方案1】:

    我找到了访问父数据的解决方案:

    Template.nestedTemplate.events({
        'click a.class':function(event,template){
            var parentID = template.data._id;
            console.log(parentID);
        }
    });
    

    .events 处理程序函数接收两个参数:event,一个包含事件信息的对象,以及 template,一个模板实例,用于定义处理程序的模板。我花了很长时间才弄清楚这一点。不要使用车把解决方案,它会显示您的数据!

    【讨论】:

    • _id 仅在您当前的数据上下文设置了该变量时才会存在。与调用this._id 相同。我不知道这将如何让您访问父母的数据?
    • 这个。将获取当前上下文(例如,如果您在 {{each}} 块中),对我来说 template 获取模板上下文,这可能与当前上下文不同。
    【解决方案2】:

    我不确定您是否可以获取父模板数据,但在您的事件处理程序中您可以访问 DOM 元素:event.currentTarget 将获取单击的元素。然后只需使用 jQuery 来访问属性。如果需要,event.currentTarget.parentNode 将获取 DOM 中的父元素。

    例如:我不知道您将标记类放在哪里,但假设它是定义 data-taggroup 的 div 的类。然后您可以使用以下方法获取标签名称:

    $(event.currentTarget).attr('data-taggroup')
    

    【讨论】:

      【解决方案3】:
      "click selected":function(e){
          // this._id
         var doc_id = $(e.currentTarget).parent().parent().attr("uid")
         console.log(doc_id) 
      },
      //specify the each id in the div above the nearest #each
      //this will work in events but not in helpers`
      

      【讨论】:

        猜你喜欢
        • 2016-04-28
        • 2014-03-12
        • 2015-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-08
        • 2016-01-09
        相关资源
        最近更新 更多