骨干.js中的渲染集合视图 [英] Rendering collection view in backbone.js
问题描述
我在理解如何使用模板在视图中呈现集合时遇到问题.这是我的代码:
I am having problems understanding how to render a collection in a view using a template. Here is my code:
<div id="mydiv"></div>
<script type="text/template" id="details">
<ul>
<% _.each(?, function(person) { %>
<li><%= person.name %></li>
<% }); %>
</ul>
</script>
<script>
var m = Backbone.Model.extend();
var c = Backbone.Collection.extend({
url: 'retrieve.php',
model: m
});
var v = Backbone.View.extend({
el : $('#mydiv'),
template : _.template($("#details").html()),
initialize : function() {
var coll = new c();
coll.fetch({success: function(){alert(JSON.stringify(coll));} });
this.render();
},
render : function() {
//what do I put here?
return this;
}
});
var view = new v();
我对如何将php文件返回的数据导入模板感到困惑.我在视图和._each中需要什么代码?我的php代码返回了:
I am confused about how to get the data returned from my php file into the template. What code do I need in the view and ._each? My php code is returning:
[{"id":"1","name":"John","age":"5"},{"id":"2","name":"Jane","age":"2"}]
并且我在alert()中看到了这一点.
and I see this in the alert().
推荐答案
您应该从success
处理程序中调用render
函数,因为collection.fetch
异步返回结果(您也可以
You should call your render
function from the success
handler as a collection.fetch
returns result asynchronously (you can also bind render
function to a collection reset
event).
var v = Backbone.View.extend({
el : '#mydiv',
template : _.template($("#details").html()),
initialize : function() {
var self = this,
coll = new c();
coll.fetch({ success: function(){ self.render() ; } });
},
render : function() {
// the persons will be "visible" in your template
this.$el.html(this.template({ persons: this.coll.toJSON() }));
return this;
}
});
并且在模板中引用相同的persons
对象
And in the template refer to the same persons
object
<script type="text/template" id="details">
<ul>
<% _.each(persons, function(person) { %>
<li><%= person.name %></li>
<% }); %>
</ul>
</script>
更新:
我已经创建了有效的 fiddle ,但是我不得不修改原始源代码因为我不能使用您的retrieve.php
端点
I've created the working fiddle, but I had to modify the original source code as I can't use your retrieve.php
endpoint
这篇关于骨干.js中的渲染集合视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!