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

时间:2011-12-22 18:19:58

标签: json backbone.js

我正在尝试使用backbone.js来加载json。 json加载但我不知道如何将项目放入我的收藏中。 或者这可能是自动发生的,我无法追踪。范围问题?

// js code

//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"
        }
    ]
}

2 个答案:

答案 0 :(得分:16)

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

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"
        }
    ]

答案 1 :(得分:0)

如果您使用rest api,请尝试关闭以下参数:

Backbone.emulateHTTP Backbone.emulateJSON