我有我的主干路由器:
var AppRouter = Backbone.Router.extend({
routes:{
"" : "productos",
},
initialize: function(){
this.productoItem = new Producto();
//Crear la vista del detalle de un producto
this.productoItems = new Productos();
this.productoItems.fetch();
this.productosView = new ProductsView({collection: this.productoItems});
},
productos: function(){
$('#app').html(this.productosView.render().el);
//this line seems not to working but putting in a console does the work
}
});
/*********************************/
var app = new AppRouter();
$(function(){
Backbone.history.start();
});
这是 View :
var ProductsView = Backbone.View.extend({
render: function(){
this.$el.html(Handlebars.templates.products(this.collection));
return this;
}
});
最后是我的 Handlebars 模板:
<h1>Y LOS MODELOS SON</h1>
<ul>
{{#each models}}
<li>
{{attributes.familia}}
</li>
{{/each}}
</ul>
所以当我运行这个应用程序时,它只呈现 Y LOS MODELOS SON 这意味着
$('#app').html(this.productosView.render().el)
;有效,但不完全只有 html 标签...但是当我这样做时:
$('#app').html(app.productosView.render().el)
在控制台中它完美地工作...... 有人可以解释一下我错过了什么吗? 谢谢...
最佳答案
Collection#fetch
是一个 AJAX 调用,因此在服务器发回任何内容之前会调用 AppRouter#productos
。结果是,当调用 ProductsView#render
时,集合为空,并且模板中的 {{#each models}}
没有任何可迭代的内容。
Collection#fetch
使用 Collection#set
将获取的模型合并到集合中。这将触发集合上的“add”
、“remove”
和“change”
事件。您可以从集合中监听这些事件并重新渲染:
initialize: function() {
this.listenTo(this.collection, 'add remove change', this.render);
}
但这将非常浪费,因为您将为每个新添加的模型重新渲染 View 。另一种方法是使用 {reset:true}
获取:
When the model data returns from the server, it uses set to (intelligently) merge the fetched models, unless you pass
{reset: true}
, in which case the collection will be (efficiently) reset.
和reset
将触发单个“reset”
事件。所以在你的路由器中,你可以说:
this.productoItems = new Productos();
this.productoItems.fetch({ reset: true });
然后在你看来:
initialize: function() {
this.listenTo(this.collection, 'reset', this.render);
}
使用 {reset: true}
似乎是您的情况下最容易使用的方法。
关于javascript - 主干渲染 View 未显示...仅在控制台中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19485115/