Meteor:绑定函数以适用于模板的每次迭代

时间:2015-12-09 10:41:57

标签: templates meteor

我对Meteor来说相当新,我无法理解如何在模板的每次迭代中使函数独立于其他模板。我已经编写了一个非常基本的功能,我希望在按钮点击时在每个模板中显示一个弹出窗口,但弹出窗口始终显示在第一个生成的模板上,而不是绑定到我单击的特定按钮。我已经四处搜索,发现它可能与模板实例或反应变量有关,但到目前为止,我很困惑。 这可能是正确的轨道吗? https://dweldon.silvrback.com/template-instance

我的代码:

html的

<body>
  {{> test}}
</body>

<template name="test">
  {{#each tasks}}
    <button type="button" id="popup">Click Me!</button>
    <div id="pops">Hi</div>
  {{/each}}
</template>

的.js

Tasks = new Mongo.Collection("tasks");

if (Meteor.isClient) {
  Template.test.helpers({
    tasks: function () {
      return Tasks.find({});
    }
  });

  Template.test.events({
    'click #popup': function(e, template) {
      template.$('#pops').fadeIn();
    }
  });
}

我根本没有在服务器代码中写任何东西。 谢谢!

2 个答案:

答案 0 :(得分:0)

尝试像这样更改您的代码

<template name="test">
{{#each tasks}}
<button type="button">Click Me!</button>
<div id={{_id}}>Hi</div>
{{/each}}
</template>

Template.test.events({
'click button': function(e, template) {
var id = '#'+this._id;
$(id).fadeIn();
}
});
}

答案 1 :(得分:0)

  1. 不要使用ID,而是使用类。为什么?因为不允许您使用具有相同ID的多个元素。
  2. 创建新模板task并在each循环中进行渲染。
  3. HTML:

    <body>
      {{> test}}
    </body>
    
    <template name="test">
      {{#each tasks}}
        {{> task}}
      {{/each}}
    </template>
    
    <template name="task">
      <button type="button" class="popup">Click Me!</button>
      <div class="pops">Hi</div>
    </template>
    

    JS:

    Template.task.events({
      'click .popup': function() {
        template.$('.pops').fadeIn();
      }
    });
    
相关问题