Last Updated: February 25, 2016
·
1.053K
· hoodwink73

Making a (backbone) collection into an iterator

Sometimes its good to have an iterator which can iterate over an collection returning attribute values for each model.

This pattern is completely inspired by Stoyan Stefanov's Iterator pattern(checkout the book)


 collection = [
  {
     "handle": "@fat", 
     "status": "Studying philosophy"
 }, 
  {
     "handle: "@addyosmani", 
     "status": "Teaching how to web"
 } 
];

 var makeIterator = function (collection, property) {
     var agg = (function (collection) {
         var index = 0,
             length = collection.length;

         return {
             next: function () {
                 var element;
                 if (!this.hasNext()) {
                     return null;
                 }
                 element = collection[index][property];
                 index = index + 1;
                 return element;
             },
             hasNext: function () {
                 return index < length;
             },
             rewind: function () {
                 index = 0;
             },
             current: function () {
                 return collection[index];
             }
         };
     })(collection);

     return agg;
 };
 var iterator = makeIterator(collection, "handle");
 // iterator.next() => "@ fat"
 // iterator.next() => "@ addyosmani"
 // iterator.next() => null