获取收集长度

Ged*_*nas 9 backbone.js

使用backbone.js并尝试从postsList数组中获取数据我在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
Run Code Online (Sandbox Code Playgroud)

当我试图使用时,console.log(postsList.length)我得到0,但里面有9个模型.我不知道如何获得它们的数量.

Vit*_*huk 11

是的,这是奇怪的行为:)

Chrome使用后会立即显示对象预览console.log.当你输入console.log(collection)它是空的(可能你从服务器获取模型).但是当您在控制台中展开对象时,Chrome会在当前时刻显示实际对象参数.

在控制台中试试这个:

var object = {key1:{prop:true}};
console.log(object)
object.key2 = true;
console.log(object)
Run Code Online (Sandbox Code Playgroud)

要获得收集长度,请使用以下方法:

collection.fetch({context:collection}).done(function() {
  console.log(this.length)
});
Run Code Online (Sandbox Code Playgroud)

编辑

不 - 不 - 使用this.length而不是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'}));
});
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请访问:http: //backbonejs.org/#Collection