【发布时间】:2017-11-09 21:44:47
【问题描述】:
我有两个在 Backbone 模型上调用 fetch 的函数。第一个使用 id 创建模型的新实例并调用 fetch(),第二个使用 id 从集合中检索现有模型实例并调用 fetch()。第一个触发了模型的解析函数,第二个没有触发……不知道为什么。
第一个(触发器解析)
App.fetchItemById = function (id) {
App.myItem = new App.Item({id: id});
App.myItem.fetch({
traditional: true,
data: {
elements: 'all',
format:'json',
},
success: function(){
App.myItemView = new App.ItemView({
el: $('#active-item'),
model: App.myItem,
});
App.myItemView.render();
}
});
};
第二个(不触发解析)
App.fetchItemFromCollectionById = function (id) {
App.myItem = App.myItemCollection.get(id);
App.myItem.fetch({
traditional: true,
data: {
elements: 'all',
format:'json',
},
success: function(){
App.myItemView = new App.ItemView({
el: $('#active-item'),
model: App.myItem,
});
App.myItemView.render();
}
});
};
我读过的所有文档都说模型的解析函数总是在 fetch 时调用。
有人知道为什么第二个没有触发解析吗?
这是模型定义:
App.Item = Backbone.Model.extend({
urlRoot: '/api/v1/item/',
defaults: {
},
initialize: function(){
},
parse : function(response){
console.log('parsing');
if (response.stat) {
if (response.content.subitems) {
this.set(‘subitems’, new App.SubitemList(response.content.subitems, {parse:true}));
delete response.content.subitems;
this
}
return response.content;
} else {
return response;
}
},
});
已修复,感谢 EMILE 和 COREY - 以下解决方案
原来,当我第一次加载 App.MyItemCollection 时,集合中的模型只是通用模型,没有正确地转换为 App.Item 的实例。将“模型:App.Item”添加到集合定义中解决了这个问题。见下文:
原创
App.ItemList = Backbone.Collection.extend({
url: '/api/v1/item/',
parse : function(response){
if (response.stat) {
return _.map(response.content, function(model, id) {
model.id = id;
return model;
});
}
}
});
更新,解决问题
App.ItemList = Backbone.Collection.extend({
url: '/api/v1/item/',
model: App.Item,
parse : function(response){
if (response.stat) {
return _.map(response.content, function(model, id) {
model.id = id;
return model;
});
}
}
});
【问题讨论】:
-
已确认。该模型在获取前和获取后都有一个 id 属性,并触发了 fetch:success 回调。
-
Backbone 的哪个版本? 1.2.0
-
我更新到 1.3.3 也遇到了同样的问题。
-
myItemCollection是什么样的?model属性是否设置为使用App.Item作为其模型? -
@CoryDanielson,就是这样!当我第一次加载集合时,我没有正确地将模型转换为 App.Item 的实例。当我添加它时,它起作用了。谢谢你。我会用工作代码更新我的问题。