Created
December 10, 2013 12:45
-
-
Save marqsm/7890048 to your computer and use it in GitHub Desktop.
Backbone collection - applyRecursive. To facilitate applying functions that need to traverse collection models and all their children.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// runs parameter function on all collection models (including children). Expects child collection to be defined in model as "nodes". | |
applyRecursive: function(func) { | |
// takes the last given function parameter - recursion makes arguments array more complex, se need to flatten it out. | |
var lastArg = _.chain(arguments).toArray().flatten().last().value(); | |
this.each(function(model) { | |
func.call(model, func, lastArg); // run function in context of the model. | |
// if has nodes, apply function to nodes. | |
if ((typeof model.nodes !== 'undefined') && (typeof model.nodes.models !== 'undefined') && (model.nodes.models.length > 0)) { | |
model.nodes.applyRecursive(func, lastArg); | |
} | |
}); | |
// TODO: should trigger an event when complete to reactions. Implement internal counter for initiated functions, to find out end of recursions. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment