user1884367
user1884367

Reputation: 425

Backbone.js adding model retrieved from server to a collection

I would like to know if it possible to add a model to a collection in the following manner. I tried it and it doesn't work. If I add the JSON [] directly it does. I know this is a little strange but I am trying to get a better understanding of how BB works. Thanks.

var UserModel = Backbone.Model.extend({
    urlRoot: '/users',
});

var UserModels = Backbone.Collection.extend({
    url: '/users',
    model: UserModel
});

var user = new UserModel({id:1});
user.fetch({  // get the model
    success: function (user) {
        var users = new UserModels();
        users.add(user); // add the model to a collection
    }
});

The following model is being echoed from the server:

[{"name":"john","email":"[email protected]"}]

Upvotes: 1

Views: 53

Answers (1)

Daniel J.G.
Daniel J.G.

Reputation: 34992

Since the response from the server is an array with a single element, you will need to add a parse function that returns the first element of the array:

var UserModel = Backbone.Model.extend({
    urlRoot: '/users',
    parse: function(response){
        if(response && response.length) return response[0];
    }
});

That should allow the model to correctly parse the attributes in this response from the server: [{"name":"john","email":"[email protected]"}].

By the way, you are creating the users collection in the success function, so it won´t be available outside that function. It might just be the sample code you posted, but you could create the users collection outside and just add the model in the success function:

var users = new UserModels();
var user = new UserModel({id:1});
user.fetch({  // get the model
    success: function (user) {
        users.add(user); // add the model to a collection
    }
});

I have created a fiddle so you can give it a try. (I have used fiddle echo service, so thats why I have changed the url and it is using a POST). If you run it and check the console, you will see the users collection being logged and you can check its models property.

Upvotes: 3

Related Questions