如何使用fetch将json添加到backbone,js集合中

Col*_*son 8 json backbone.js

我试图让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();
Run Code Online (Sandbox Code Playgroud)

// JSON

{
    "items": [
        {
            "name": "WTBS",
            "img": "no image"
        },

        {
            "name": "XYC",
            "img": "no image"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

Esa*_*ija 16

您的json格式不正确,您可以在解析方法中修复json或向骨干添加提示:

var ClientCollection = Backbone.Collection.extend({
    defaults: {
        model: Client
    },
    model: Client,
    url: 'json/client.json',

    parse: function(response){
       return response.items;
    }
});
Run Code Online (Sandbox Code Playgroud)

或者修复你的JSON:

 [
        {
            "name": "WTBS",
            "img": "no image"
        },

        {
            "name": "XYC",
            "img": "no image"
        }
    ]
Run Code Online (Sandbox Code Playgroud)