Gediminas Šukys
Gediminas Šukys

Reputation: 7391

Get collection length

Using backbone.js and trying to get data from postsList array I got this in chrome console.log

d {length: 0, models: Array[0], _byId: Object, _byCid: Object, constructor: function…}
  _byCid: Object
  _byId: Object
  length: 9
  models: Array[9]
  __proto__: f

When I'm trying to use console.log(postsList.length) I get 0, but there are 9 models inside. I don't know how to get number of them.

Upvotes: 9

Views: 27535

Answers (2)

bgraves
bgraves

Reputation: 839

I think Vitaliys answer is a little bit dangerous, because the passed option {context: collection} is:

  • a) not mentioned in backbones documentation
  • b) handled deep down in jQuery when fetch triggers some Ajax-call.

Instead the length of the fetched collection can be easily checked in the success- and error- callback of fetch, e.g.:

someCollection.fetch({
    success: function(collection) { // the fetched collection!
        if (collection.length) {
            // not empty
        } else {
            // empty
        }
    }
});

See http://backbonejs.org/#Collection-fetch

Upvotes: 3

Vitalii Petrychuk
Vitalii Petrychuk

Reputation: 14255

Yes, this is strange behaviour :)

Chrome displays object preview immediately after you have used console.log. When you entered console.log(collection) it was empty (probably you have fetched model from the server). But at the moment when you expand the object in console Chrome displays actual object params at current moment.

Try this in console:

var object = {key1:{prop:true}};
console.log(object)
object.key2 = true;
console.log(object)

To get collection length use this way:

collection.fetch({context:collection}).done(function() {
  console.log(this.length)
});

EDIT

No-no-no :) Use this.length instead of this.lenght.

collection.fetch({context:collection}).done(function() {
    // equals to this.length
    console.log(this.size());
    // get all models from collection (array of Backbone.Models)
    console.log(this.models);
    // get all models from collection (like simple array of objects)
    console.log(this.toJSON());
    // get model with index 1
    console.log(this.at(1));
    // get model data with index 1
    console.log(this.at(1).toJSON());
    // get model with id `some-id`
    console.log(this.get('some-id'));
    // get models data where property `id_str` equals to `292724698935070722`
    console.log(this.where({id_str:'292724698935070722'}));
});

For more information look here: http://backbonejs.org/#Collection

Upvotes: 12

Related Questions