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

2024-01-10

我正在尝试让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"
        }
    ]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用fetch将json添加到backbone,js集合 的相关文章

随机推荐