Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my backbone.js collection reset is only adding 1 model

The collection in question grabs a bunch of Friends, and then it uses reset to save all the new Friends. The problem I am having, is that it only adds 1 friend to the collection.

I did a console.log on cModels and it was showing over 300 objects in the Array, so I know there isn't only 1. Any reason why the reset would only be adding 1?

Here is my collection:

FriendsCollection = Backbone.Collection.extend({
    model: UserModel,

    getFriends: function () {
        $.post(baseUrl + dataFriendsUrl, $.proxy(function(data) {
            var friends = $.parseJSON(data);
            var cModels = [];

            for(var key in friends.data) {                
                var user = new UserModel();
                user.set({
                    fbid: friends.data[key].id,
                    username: friends.data[key].name
                });

                cModels.push(user);
            }

            this.reset(cModels);

            console.log(this);

        }, this));
    }
});

And the models look fine, after inspecting them with the developer tools.

like image 360
xil3 Avatar asked Jul 06 '12 20:07

xil3


People also ask

How can we get the attribute value of a model in Backbone JS?

js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)

What is module in Backbone JS?

js respectively. The rest of your application code should be divided into modules that can live under their own modules directory. A module is an encapsulated group of structures (for the purposes of our post, Backbone structures) that work cohesively to provide a subset of functionality in your application.

Who created backbone JS?

Backbone was created by Jeremy Ashkenas, who is also known for CoffeeScript and Underscore.js.


1 Answers

It's probably because the models have the same id.

A Backbone collection does not allow models with duplicate id values. (see this commit)

like image 150
Paul Avatar answered Oct 13 '22 07:10

Paul