2013-10-21 52 views
1

我有我的骨幹路由器:骨幹渲染視圖不顯示...只有在控制檯

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(); 
}); 

繼承人的看法:

var ProductsView = Backbone.View.extend({ 

    render: function(){ 
     this.$el.html(Handlebars.templates.products(this.collection)); 
     return this; 
    } 
}); 

最後我的車把模板:

<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) 

在控制檯它完美... 有人可以解釋我我失去了什麼? 謝謝...

回答

0

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); 
} 

但是這將是非常浪費的,你會重新呈現每一個新加入的模型視圖。另一種方法是用{reset:true}獲取:

當從服務器模型數據的回報,它採用設置到(智能)合併所取得的模型,除非你通過{reset: true},在這種情況下,收集會(高效)重置

and reset將觸發單個"reset"事件。因此,在你的路由器,你可以說:

this.productoItems = new Productos(); 
this.productoItems.fetch({ reset: true }); 

,然後在您的視圖:

initialize: function() { 
    this.listenTo(this.collection, 'reset', this.render); 
} 

使用{reset: true}似乎是最簡單的事情在你的情況下使用。

+0

非常感謝!它的工作...不知道在獲取觸發事件... –