问题
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:
- Don't use IDs, use classes instead. Why? Because you are not allowed to have several elements with the same ID.
- Create new template
task
and render it insideeach
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