2012-11-24 133 views
2

我正在学习如何使用Backbone和Parse创建一个调查网站。 我见过堆栈溢出的类似问题。不过,我的问题有点不同。 在本网站上,用户可以进行自己的调查。现在假设用户可以发布两种类型的问题:多种选择和自由回应。我创建了一个名为Question的骨干模型,如下所示。骨干:一个模型两个视图?

//问题型号

//---------------------- 
var Question = Parse.Object.extend(
"Question", { 
//Default attributes for the todo 
defaults: { 
    content: "What's your name", 
    type: "free_response", 
    choices: [] 
}, 
initialize: function() { 
     if (!this.get("content")) { 
       this.set({"content": this.defaults.content}); 
    } 
     if (!this.get("type")) { 
       this.set({"type": this.defaults.type}); 
    } 
     if (!this.get("choices")) { 
       this.set({"choices": this.defaults.choices}); 
    } 
} 

}); 

所以我也想创建QuestionView可显示的问题。但它应该有不同的选择和自由回应。 那么根据其类型显示不同的问题的最佳方式是什么? 谢谢。

+1

你为什么手动应用的默认值?在'defaults'中使用数组可能会导致问题,如果要包含可变值,则应该为'defaults'使用函数。 –

+0

是的,我确实遇到了数组问题,它似乎没有做我所期望的(这是我可以追加项目到数组)。通过使用函数进行默认值,你的意思是什么? – user1849043

+0

您可以使用函数['defaults'](http://backbonejs.org/#Model-defaults)而不是对象:'defaults:function(){return {...}}'。这会给你一个不同的模型默认设置。 –

回答

0

在你questionView模板添加一个if声明:

<script type="template/underscore" id="QuestionView"> 
<%- content %> 
<% if (type === 'free_response') { %> 
<textarea name="answer<%- id %>"></textarea> 
<% } else { _(choices).each(function (choice) { %> 
<input type="radio" name="answer<%- id %>" value="<%- choice %>"> <%- choice %> 
<% });} %> 
</script> 

更多关于如何使用下划线模板见: http://documentcloud.github.com/underscore/#template

+0

非常感谢!你的建议非常有帮助! – user1849043

+0

对不起,你可以进一步解释一下这一行:?谢谢! – user1849043

+0

我的意思是我不完全确定什么名称=“回答<%- id %>”。是否用于稍后检索用户的答案? – user1849043

相关问题