【发布时间】:2016-05-01 18:35:45
【问题描述】:
在模型上执行提取操作时,我可以看到 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();
如何使用新数据正确更新视图?
如果我从模型中删除默认值,则未定义“内容”。
【问题讨论】:
-
奇怪的是
changed: Object变成了changed: Object[1],。 API 返回的数据结构是怎样的? BTW id 是主干使用的特殊属性。 -
返回的数据是一个json对象 [{ "id":"1", "owner":"1", "created":"2016-04-30 21:57:23", "lastupdate":null, "content":"API 获取成功" }]
-
这意味着您需要在 Backbone 将响应设置为模型属性之前实现
parse()来处理响应,或者您需要从Collection获取该 REST 资源。