[英]Backbone fetch model then render view
在模型上執行提取操作時,可以看到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();
如何使用新數據正確更新視圖?
如果我從模型中刪除默認值,則不會定義“內容”。
您可以在模型上偵聽Backbone sync
事件。 成功調用服務器后觸發sync
this.listenTo(this.model, 'sync', this.render);
您也可以在initialize方法App.Views.DocumentView
模型獲取移動到App.Views.DocumentView
。 然后,成功渲染視圖:
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() {
var self = this;
// model fetch
this.model.fetch({
success: function() {
// call render
self.render();
},
error: function () {
// handle error
}
});
// 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;
}
});
var myModel = new App.Models.Document();
var myView = new App.Views.DocumentView({
model: myModel
});
myView.render();
Backbone.Model期望從服務器而不是數組中返回一個對象。 如果是集合,則應返回一個數組。
因此,在您的情況下,您需要定義一個parse
方法以返回包含數據的對象:
App.Models.Document = Backbone.Model.extend({
defaults: {
owner: 0,
created: '',
lastupdate: '',
content: 'Default document content'
},
url: '/api/',
parse: function(response) {
return response[0];
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.