A
A
Alexander2015-01-05 23:38:38
backbone.js
Alexander, 2015-01-05 23:38:38

Why doesn't eahe work for the collection?

Why doesn't the each method work for the collection, it's just an object??? it's probably useless, but still, why doesn't it work, breeed ....

var col1 = new Backbone.Collection()

  col1.add([{name: 'Ivan', age: 24},{name: 'Alex', age: 22}])
  console.log( col1 ) // Почему выводится коллекция содержащийся модели которые добавил на следующей строчки?
  col1.set([{name: 'Djon', age: 21},{name: 'Tom', age: 32},{name: 'Roman', age: 19}])

  console.log( '=====================================' )

  _.each(col1, function(val, key){
    console.log( key, val )  
  })
       //Выводит:
       //undefined 0 
       //undefined 1 
       //undefined 2

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
aen, 2015-01-06
@aen

The method eachiterates an object by its properties, or an array by elements. In your case, the iteration is over the object. That's just the collection models to lie in the property of modelsyour collection. So iterate over it. I.e:

_.each(col1.models, function(val, key){
    console.log( key, val )  
  })

For convenience, you can create your own "class" of collections and extend it with the method each:
var Collection = Backbone.Collection.extend({
  each: function (fn) {
    _.each(this.models, fn);
  }
});

var myColl = new Collection();

// Итерирование
myColl.each(function(model) {
    // какая-то логика работы с моделью
});

Similar questions

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question