javascript - Backbone Collection filter method -


can explain mechanics behind filter() method exists within collection "class"? backbone api method appears inconsistent following example implementation (taken todo exercise @ http://addyosmani.github.io/backbone-fundamentals/):

completed: function() {     return this.filter(function( todo ) {         return todo.get('completed');     }); } 

this code snippet produces array of model objects who's 'completed' property contains "true". however, cannot come close understanding how array of objects returned function

the key curiosity lies in underscores source code. know, large number of methods available on backbone.collection brought in underscore.

let's take @ how first:

// underscore methods want implement on collection. // 90% of core usefulness of backbone collections implemented // right here: var methods = ['foreach', 'each', 'map', 'collect', 'reduce', 'foldl', 'inject', 'reduceright', 'foldr', 'find', 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', 'max', 'min', 'toarray', 'size', 'first', 'head', 'take', 'initial', 'rest', 'tail', 'drop', 'last', 'without', 'difference', 'indexof', 'shuffle', 'lastindexof', 'isempty', 'chain'];  // mix in each underscore method proxy `collection#models`. _.each(methods, function(method) {     collection.prototype[method] = function() {        // important: bolt on collection models arguments.       var args = slice.call(arguments);       args.unshift(this.models);        // .apply (since have array of arguments).       return _[method].apply(_, args);     }; }); 

so have list of underscore method names. source code loops through method names , adds each 1 collections prototype. important: you'll notice code patches argument list include in collection's models.

now @ underscore's actual method implementation:

_.filter = _.select = function(obj, iterator, context) {   var results = [];   if (obj == null) return results;   if (nativefilter && obj.filter === nativefilter) return obj.filter(iterator, context);    each(obj, function(value, index, list) {     if (iterator.call(context, value, index, list)) results.push(value);   });    return results; } 

you'll notice filter wraps around each , cycles through passed in object (properties). backbone version put method context save having pass in models each time.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -