基于动态模板向集合添加元素 [英] Add elements to collection based on a dynamic template

查看:61
本文介绍了基于动态模板向集合添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个投票模板,可以有用户想要的尽可能多的问题.如何将所有问题插入到集合的元素中?由于我之前只有三个,所以我像这样手动插入它们:

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?

推荐答案

如果你已经实现了一个本地集合来存储 Choices 相关数据,你可以使用 cursor.map() 函数循环您的集合,将适当的对象返回到数组中,最后设置相应的数据:

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

这篇关于基于动态模板向集合添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆