问题
So I have a poll template that can have as many questions as the user wants. How do I insert all the questions into an element of a collection? Since I only had three before, I inserted them manually like this:
var newPoll = {
question: event.target.question.value,
choices: [
{ text: event.target.choice1.value, votes: 0 },
{ text: event.target.choice2.value, votes: 0 },
{ text: event.target.choice3.value, votes: 0 }
],
usersWhoVoted: [],
poll_is_open: true,
time_poll_closed: null,
};
If I can have now as many choices as I want, how do I insert all of them?
回答1:
If you have implemented a local collection to store Choices
related data, you could use the cursor.map() function to loop over your collection, return proper objects into an array and finally set the corresponding data:
if (Meteor.isClient) {
Template.pollForm.events({
'click #save-form': function(event, template) {
var choices = Choices.find().map((choice) => ({
text: template.find("input[name=" + choice.name + "]").value,
votes: 0
}));
var newPoll = {
question: event.target.question.value,
choices: choices,
usersWhoVoted: [],
poll_is_open: true,
time_poll_closed: null
};
Polls.insert(newPoll);
}
});
}
来源:https://stackoverflow.com/questions/33975864/add-elements-to-collection-based-on-a-dynamic-template