Backbone.js Collections not applying Models (using

2019-05-28 20:24发布

问题:

I'm attempting to develop a site using CodeIgniter and Backbone.js, but I'm running into an issue when attempting to set Models to a Collection I have called fetch() on. I am using the REST API by Phil Sturgeon, and am receiving a JSON response when using fetch() on the Collection, but no children Models are added to it.

Here's the javascript I'm using:

$(document).ready(function() {
    window.Person = Backbone.Model.extend({});
    window.People = Backbone.Collection.extend({
        model: Person,
        url: "/api/content/users/format/json"
    });
});

And my CI Controller:

require APPPATH.'/libraries/REST_Controller.php';

class Content extends REST_Controller   {    
    function users_get()    {       
        $users = array(
            array('id' => 1, 'name' => 'Some Guy', 'email' => 'example1@example.com'),
            array('id' => 2, 'name' => 'Person Face', 'email' => 'example2@example.com')
    );

        if($users) {
            $this->response($users, 200); // 200 being the HTTP response code
        } else {
            $this->response(array('error' => 'Couldn\'t find any users!'), 404);
        }
    }
}

And when attempting to fetch() the Models for the Collection via the console like:

peoples = new People();
peoples.fetch();
peoples.models;

It gets the JSON response, but still says 'There are no child objects' (see image):

http://i.stack.imgur.com/e5vZv.png

Any idea what is going wrong? Totally stumped!

回答1:

Explications

It's normal that people.models is empty directly after the fetch() call, you need to wait the end of the ajax request.

Indeed, fetch() is asynchronous and the Backbone JS documention says :

collection.fetch([options])

[...] The options hash takes success and error callbacks which will be passed (collection, response) as arguments.

Source: http://documentcloud.github.com/backbone/#Collection-fetch

Solution

You need to use :

peoples = new People();
peoples.fetch({
    success: function (collection, response) {
        // The collection is filled
        console.log('Models : ', peoples.models);
    }
});