2014-07-02 614 views
0

我試圖用一個新的項目添加到我的收藏骨幹取前:骨幹:渲染

window.bearList.create({ name: "Tina" }); 

這正確保存到服務器上的新項目,因爲後來我可以看到這個服務器上,這是我想要的。 (我使用的MongoDB)

{"name":"Tina","_id":"53b41d92b7083d0b00000009","__v":0} 

在我bearList的ListView我有這樣的結合:

initialize: function() { 
     _.bindAll(this, 'render'); 
     this.collection.bind('add', this.render); 
    }, 

的問題是,剛纔上面的代碼添加到我重新加載頁面下面我收集視圖。

{"name":"Tina"} 

我試過使用model.save()回調,但我仍然有同樣的問題。

就像我說過的,服務器上的所有東西看起來都不錯,而且一旦我重新加載頁面,集合就有'Tina'的修正版本。

但由於某種原因,它沒有得到ListView的'render'事件的完整模型。我已經嘗試在ListView渲染方法上單獨獲取每個模型,但這不起作用,無論如何都是不好的做法。

有人可以幫我嗎?

這裏是我的完整代碼如下:

window.ListView = Backbone.View.extend({ 
    tagName: 'ul', 
    className: 'list-group', 

    initialize: function() { 
     _.bindAll(this, 'render'); 
     this.collection.bind('add', this.render); 
    }, 

    render: function(){ 
     this.$el.html(" "); 
     this.collection.each(function(item){ 
     var listItemView = new ListItemView({ model: item }); 
     this.$el.append(listItemView.render().el); 
     }, this); 
    return this; 
    }, 

}); 



window.ListItemView = Backbone.View.extend({ 
    tagName: 'li', 
    className: 'list-group-item', 

    initialize:function() { 
     this.model.bind("change", this.render); 
    }, 

    render:function() { 
     console.log(JSON.stringify(this.model.toJSON())); 
     this.$el.html("<a href='#"+ this.model.hashType + "/"+this.model.get('_id')+"' >" + this.model.get('name') + "</a>"); 
    return this; 
    } 
}); 

回答

0

只是通過等待:真實。

window.bearList.create({ name: "Tina" }, {wait: true}); 

http://backbonejs.org/#Collection-create

通行證{等待:真正}如果你想添加 新模式集合之前等待服務器。

+0

我沒有看到,但它仍然沒有給我完整模型渲染功能。我只是得到這樣的服務器響應:'{「name」:「Tina」,「message」:「Bear created!」}' – user3783608

+0

聽取「sync」而不是add,同時確保服務器響應包含_id 。 Per Backbone文檔:以及一個「同步」事件,一旦服務器迴應成功創建模型 –

+0

好的,謝謝。我只是修改我的API返回完整的JSON,而不是「熊創建」。這是行得通的 – user3783608

0

收聽sync事件,因爲add只會添加您在主幹內創建的值。 http://backbonejs.org/#Sync

並提示:使用listenTo可以使用更多的Backbone功能。的 代替

initialize:function() { 
    this.model.bind("change", this.render); 
}, 

使用:

initialize:function() { 
    this.listenTo(this.model, "change", this.render); 
},