Backbone.js使用单个模型执行每个循环
我有以下代码:Backbone.js使用单个模型执行每个循环,backbone.js,underscore.js,Backbone.js,Underscore.js,我有以下代码: <script type="text/template" id="iterator_template"> <table> <% _.each(value, function(user) { %> <tr><td><%= user.name %></td> <td><%= user.email %></td></tr> <% }); %>
<script type="text/template" id="iterator_template">
<table>
<% _.each(value, function(user) { %>
<tr><td><%= user.name %></td>
<td><%= user.email %></td></tr>
<% }); %>
</tr></table>
</script>
<div id ="iterator_container"></div>
<script type="text/javascript">
(function($){
var UserModel = Backbone.Model.extend({
urlRoot: 'http://localhost/backbone/users',
});
IteratorView = Backbone.View.extend({
el: '#iterator_container',
initialize: function(){
var self = this;
var userDetails = {id:2};
self.user = new UserModel(userDetails);
self.user.fetch({
success: function (user) {
self.render();
}
});
},
render: function(){
var template = _.template( $("#iterator_template").html(), {value: this.user}
);
this.$el.html( template );
},
});
var form_view = new IteratorView();
})(jQuery);
没有输出
如果服务器返回:
[{"name":"John Hancock","email":"johnhancock@backbone.com"}] ... 1.
{"name":"John Hancock","email":"johnhancock@backbone.com"}
循环执行两次
我希望循环使用1执行一次。如何实现这一点?不需要循环,因为它只向模板传递一个模型,如果传递集合,则应该使用循环
<script type="text/template" id="iterator_template">
<table>
<tr><td><%= user.name %></td>
<td><%= user.email %></td></tr>
</tr></table>
</script>
是对象,因此它不工作
编辑:回答您的评论
在模型中编写此解析函数
parse : function(response){
return response[0];
}
这将从对象返回数组并将值设置为model
现在在success
调用模型添加到集合中
mymodel.fetch({
success : function(){
mycollction.add(mymodel);
}
})
保留问题中的模板,现在将此
集合作为JSON
传递给模板是的,我理解你的意思。问题是我的代码将JSON作为[]返回。如果我有一个由单个模型组成的集合,那么这个结构可以工作。也许答案是获取模型并将其插入到集合中,然后迭代该集合。但是不知道该怎么做。如果服务器返回一个数组,为什么不获取一个集合而不是模型
?或者,您可以使用parse
仅返回数组的第一个对象。@user1884367您是否可以检查答案和注释Yes,用您的代码覆盖默认的parse方法,然后将模型添加到集合中,这样做非常有效。谢谢你的帮助。
mymodel.fetch({
success : function(){
mycollction.add(mymodel);
}
})