Why fetch() does not work?

2019-01-28 14:14发布

问题:

I'm trying to fetch a collection from a JSON url. The backbone does send the request and does get a response but there are no models in the collection after it:

Here is my JavaScript:

stores.fetch();

JSON in the response

[{"name":"Store 1"},{"name":"Store 2"},{"name":"Store 3"},{"name":"Store 4"}]

The Content-Type HTTP header in the response is application/json.

Why doesn't it load into the collection? Is the JSON correct?

Some more code:

be.storeList.Item = Backbone.Model.extend({
    defaults: {
        id: null,
        name: null,
        description: null
    },
    initialize:function(attrs){
        attrs.id = this.cid;
        this.set(attrs);
    }
});

be.storeList.Items = Backbone.Collection.extend({
    model: be.storeList.Item,
    url:'/admin/stores'
});

var stores = new be.storeList.Items();
stores.fetch();
console.log(stores.toJSON());

回答1:

fetchis asynchronous. Try

stores.fetch({ 
    success:function() {
        console.log(stores.toJSON());
    }
});

or

stores.on("sync", function() {
    console.log(stores.toJSON());
});
stores.fetch();

or

stores.fetch().then(function() {
    console.log(stores.toJSON());
});


回答2:

Get rid of the initialize function in your Item class. You don't need it.

There's no such thing as stores.models -- if you want to see what's in it, you have to do console.log(stores.toJSON());