Building Collections Using Lodash Invoke
Sometimes it's useful to build collections by mapping the results of method invocations.
by Adam Boduch
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
JavaScript
var coll1 = new Backbone.Collection(),
coll2 = new Backbone.Collection(),
coll3 = new Backbone.Collection(),
colls = [ coll1, coll2, coll3 ];
/*
* Returns true if each collection in the array
* is empty. We use _.invoke() to build the new
* collection of true/false values, and
* _.compact() to remove the false values. If
* new array isn't empty, then at least one
* of the collections is empty.
*
*/
function isEmpty( collections ) {
return _( collections )
.invoke( 'isEmpty' )
.compact()
.size() !== 0;
}
if ( isEmpty( colls ) ) {
console.debug( 'collections empty' );
}
coll1.add( {} );
coll2.add( {} );
coll3.add( {} );
if ( !isEmpty( colls ) ) {
console.debug( 'collections have data' );
}