Meteor: Bind function to work for every iteration of template

好久不见. 提交于 2020-01-06 19:38:06

问题


I'm fairly new to Meteor and I can't get my head around how to get a function to work in every iteration of a template independently from the others. I've written a very basic function where I want to display a pop up inside each template on button click, but the pop up always appears at the first generated template instead of being bound to the specific button I click. I've searched around and found that it might have to do with template instances or reactive variables but as of now I'm rather confused. Could this be on the right track? https://dweldon.silvrback.com/template-instance

My code:

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

I haven't written anything in the server code at all. Thanks!


回答1:


  1. Don't use IDs, use classes instead. Why? Because you are not allowed to have several elements with the same ID.
  2. Create new template task and render it inside each loop.

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



回答2:


try changing your code like this

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


来源:https://stackoverflow.com/questions/34176740/meteor-bind-function-to-work-for-every-iteration-of-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!