【问题标题】:accessing _id from template event listener in spacebars #each loop从空格键中的模板事件侦听器访问 _id #each 循环
【发布时间】:2018-01-11 18:31:06
【问题描述】:

所以我知道如果我有以下html:

<template name="myTemplate">
  <ul>
    {{#each events}}
      <li>
        <h4 class="divEvent">{{title}}</h4>
      </li>
    {{/each}}
  </ul>
</div>

我可以使用以下事件侦听器访问事件的 _id:

Template.myTemplate.events({
  'click li': function( event, template ){
    console.log( this._id );
  }
});

但如果我的 html 看起来像这样:

<template name="myTemplate">
  <ul>
    {{#each year in getYears}}
      <li>
        <h2>{{year}}</h2>
      </li>
      <ul>
        {{#each monthNumber in (getMonths year)}}
        <li>
          <h3>{{monthName monthNumber}}</h3>
        </li>
        <ul>
          {{#each event in (getEvents monthNumber year)}}
            <li class="eventLi">
              <h4>{{event.title}}</h4>
              <div>{{dayOfWeek event.start}}</div>
            </li>
          {{/each}}
        </ul>
      {{/each}}
    </ul>
{{/each}}

那么当我点击 .eventLi 时如何访问事件的 _id?

this._id 对我没有任何作用...

我确信这很明显,但我只是在学习这一切,我已经坚持了一段时间。感谢您的帮助!

【问题讨论】:

  • 我怀疑它会是this.event._id,因为#each event in... 而不仅仅是#each event。如有疑问,console.log(this)
  • 不幸的是,这对我不起作用。我按照建议做了,我得到:console.log(this) // {main: function}
  • 你试过'click .eventLi' : function() 吗?

标签: javascript meteor meteor-blaze spacebars


【解决方案1】:

使用 Blaze 解决此问题的简单模式通常是将循环中的部分放入单独的模板中,以便您可以在其中明确附加事件。 (例如,您的模板有多个 &lt;li&gt; 标签)

代替:

{{#each event in (getEvents monthNumber year)}}
  <li class="eventLi">
    <h4>{{event.title}}</h4>
    <div>{{dayOfWeek event.start}}</div>
  </li>
{{/each}}

有:

{{#each event in (getEvents monthNumber year)}}
  {{> oneEvent}}
{{/each}}

然后:

<template name="oneEvent">
  <li class="eventLi">
    <h4>{{event.title}}</h4>
    <div>{{dayOfWeek event.start}}</div>
  </li>
</template>

现在将您的事件附加到内部模板:

Template.oneEvent.events({
  'click li'( event, template ) {
    console.log( this._id );
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-10
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    • 2012-07-03
    • 1970-01-01
    • 2019-07-07
    相关资源
    最近更新 更多