Answer the question
In order to leave comments, you need to log in
Backbone.Collection and Symbol.iterator, how to do better?
ES2015 aka ES6 aka Harmony is coming. It's time to practice on home projects!
There is a ready-made function that takes an array of objects of the form {entities: []} as input and iterates over them, like this:
function iterateEntities (arr, iterator) {
for (let item of arr) {
for (let [index, entity] of item.entities.entries()) {
iterator(entity, index, item);
}
}
}
'use strict';
import Skull from 'backbone-skull';
function collectionIterator (models) {
return {
_i: -1,
next: function () {
return {
value: models[this._i + 1].attributes,
done: models.length - 1 === ++this._i
}
}
}
}
class CollectionAbstract extends Skull.Collection {
[Symbol.iterator] () {
return collectionIterator(this.models);
}
}
export default CollectionAbstract;
++this._i
? I don't understand generators well, maybe it will be better with them?
Answer the question
In order to leave comments, you need to log in
The correct answer is, indeed, generators :
function* collectionIterator (models) {
for (let model of models) {
yield model.attributes;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question