骨干:一个模型两个视图?

时间:2012-11-24 06:55:32

标签: model-view-controller backbone.js

我正在学习如何使用Backbone和Parse创建一个调查网站。 我在Stack Overflow上看到过类似的问题。但是我的问题有点不同。 在该网站上,用户可以进行自己的调查。现在假设用户可以发布两种类型的问题:多种选择和免费响应。我创建了一个名为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 个答案:

答案 0 :(得分: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