//Declare model
app.models.Items =Backbone.Model.extend({
defaults: {
id: '',
name : ''
}
});
//fetch data using collection
app.models.ItemsCollection = Backbone.Collection.extend({
model: app.models.Items,
url: urlprefix + id + "/items",
});
//Create Instance of Collection
app.models.ItemsModel = new app.models.ItemsCollection();
app.models.ItemsModel.fetch({
async: false,
// in success get response and add response in model
success: function(response) {
for (i = 0 ;i < response.models[0].attributes.elements.length;i++){
app.models.ItemsModel.add(new app.models.Items(response.models[0].attributes.elements[i]));
}
},
error: function (errorResponse) {
console.log(errorResponse);
}
});
在控制器中,我必须在我的模型中设置新属性,但我没有 得到模型。在控制台我尝试了item.models [0]来获取第一个模型,但它显示 我未定义。
var item = new app.models.Items();
item.set("Id", 'TG');
item.set("name", 'Gokul');
item.save(null, {
success: function(model, response){
console.log("save");
},
error: function(error, response){
console.log("Error: while saving Account data:" +JSON.stringify(error));
}
});
我是backbone.js的新手,请帮助我。如果我在我的代码中做错了什么
答案 0 :(得分:-1)
这里有几个问题:
在集合上调用fetch时没有async:false选项。当您调用fetch()时,将对服务器进行异步调用以获取结果。发生这种情况时,您不希望浏览器挂起。
您无需在集合中设置单个模型。假设您的REST端点返回有效的JSON,Backbone会为您执行此操作。
我会在你的成功方法中摆脱for循环。你不需要这样做。
如有必要,您可以覆盖模型定义中的解析选项,以处理每个模型的响应的自定义处理。
您还希望在模型定义中设置urlRoot,以便您可以像使用那样在集合外部使用模型。
最后,看起来您的集合中的url属性设置不正确。你不希望那里有 id 。
总而言之,您的代码应如下所示:
app.models.Items =Backbone.Model.extend({
urlRoot: urlprefix + '/items',
defaults: {
id: '',
name : ''
},
parse: function(response, options) {
//your custom code here if necessary
}
});
app.models.ItemsCollection = Backbone.Collection.extend({
model: app.models.Items,
url: urlprefix + "/items",
});
就是这样。然后,您可以创建一个集合并获取当前项目:
var items = new app.models.ItemsCollection();
items.fetch();
但请记住,fetch()是一种异步方法。您必须等待结果从服务器返回,然后才能收到集合中的任何项目。这就是成功选择的目的。
而且,您现在可以像您一样独立创建项目,现在urlRoot已在模型上设置,它应该正确保存到您的服务器。
// Not sure you want to be setting the ID here in case you want it to
// be set on the server when it is persisted
var item = new app.models.Item({
"name": "Gokul"
});
item.save();
然后,您可以手动将项目添加到您的收藏集中:
items.add(item);
或者你可以再次获取这些项目,现在它应该在那里:
items.fetch();
再次记住,fetch()只有在您等待项目首先保存到服务器(异步)时才会起作用。
祝你好运!