在模型上執行提取操作時,我可以看到API以JSON格式返回所需的數據。記錄模型的控制檯在「更改」對象中顯示新數據。骨幹提取模型然後渲染視圖
前後取:
Object {
cid: "c1",
attributes: Object,
_changing: false,
_previousAttributes: Object,
changed: Object,
id: undefined,
_pending: false
}
Object {
cid: "c1",
attributes: Object,
_changing: false,
_previousAttributes: Object,
changed: Object[1],
id: undefined,
_pending: false
}
的數據顯然是牽強,它是出現在模型中。但是,在渲染時,會顯示默認值。
App.Models.Document = Backbone.Model.extend({
defaults: {
id: '',
owner: 0,
created: '',
lastupdate: '',
content: 'Default document content'
},
url: '/api/'
});
App.Views.DocumentView = Backbone.View.extend({
tagName: 'textarea',
className: 'editor',
template: App.Template('editortemplate'),
initialize: function() {
// As proposed in so many similar questions
this.listenTo(this.model, "change", this.render);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
$(".app-content").html(this.$el);
return this;
}
});
a = new App.Models.Document();
a.fetch();
b = new App.Views.DocumentView({ model: a });
b.render();
如何使用新數據正確更新視圖?
如果我從模型中刪除默認值,'content'沒有被定義。
這很奇怪的是'改變:Object'改變'改變:對象[1],'。什麼是從API返回的數據結構? BTW id是主幹使用的特殊屬性。 –
返回的數據是一個JSON對象 [{ 「ID」: 「1」, 「所有者」: 「1」, 「創建」: 「2016年4月30日21點57分23秒」, 「 lastupdate「:null, 」content「:」API成功提取「 }] – hesonline
這意味着在Backbone將其設置爲模型屬性之前需要執行'parse()'處理響應,或者需要從來自['Collection'](http://backbonejs.org/#Collection)的REST資源。 –