Add elements to collection based on a dynamic template

北慕城南 提交于 2020-01-17 05:07:27

问题


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

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