Friday, June 27, 2014

Building Collections Using Lodash Invoke

The Lodash invoke() function does more than simply iterate over a given collection, calling the given method on each object. It actually stores the result of each method invocation, effectively building a new collection. This is a powerful idea, especially when it comes to chaining Lodash functions together.

Here's an example that uses invoke(), compact(), and size(), to determine whether the Backbone collections in question are empty. It's a much nicer approach than individually checking if each collection is populated or not.

var coll1 = new Backbone.Collection(),
    coll2 = new Backbone.Collection(),
    coll3 = new Backbone.Collection(),
    colls = [ coll1, coll2, coll3 ];

function isEmpty( collections ) {
    return _( collections )
        .invoke( 'isEmpty' )
        .size() !== 0;

if ( isEmpty( colls ) ) {
    console.debug( 'collections empty' );    

coll1.add( {} );
coll2.add( {} );
coll3.add( {} );

if ( !isEmpty( colls ) ) {
    console.debug( 'collections have data' );

Here, we have three Backbone collections. We also have an array — colls — that holds a reference to each one of these collections. The isEmpty() function we've defined expects an array like colls, so it can build a Lodash object, and chain together some function calls. The isEmpty() function works by first calling invoke() on the isEmpty() Backbone collection method. This builds a new collection of true/false values. Next, we use compact() to remove the false values — this builds yet another collection in the chain. Lastly, we check the size of the resulting collection and if it's empty, we know that all the passed-in Backbone collections have data.