我正在尝试让backbone.js 加载json。
json 已加载,但我不确定如何将这些项目放入我的收藏中。
或者这可能会自动发生,而我无法追踪。范围问题?
//js代码
//model
var Client = Backbone.Model.extend({
defaults: {
name: 'nike',
img: "http://www.rcolepeterson.com/cole.jpg"
},
});
//collection
var ClientCollection = Backbone.Collection.extend({
defaults: {
model: Client
},
model: Client,
url: 'json/client.json'
});
//view
var theView = Backbone.View.extend({
initialize: function () {
this.collection = new ClientCollection();
this.collection.bind("reset", this.render, this);
this.collection.bind("change", this.render, this);
this.collection.fetch();
},
render: function () {
alert("test" + this.collection.toJSON());
}
});
var myView = new theView();
//json
{
"items": [
{
"name": "WTBS",
"img": "no image"
},
{
"name": "XYC",
"img": "no image"
}
]
}
最佳答案
您的 json 格式不正确,您可以修复 json 或在 parse 方法中向主干添加提示:
var ClientCollection = Backbone.Collection.extend({
defaults: {
model: Client
},
model: Client,
url: 'json/client.json',
parse: function(response){
return response.items;
}
});
或修复您的 JSON:
[
{
"name": "WTBS",
"img": "no image"
},
{
"name": "XYC",
"img": "no image"
}
]
关于json - 如何使用 fetch 将 json 添加到主干、js 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8608184/