Filtering Models When Cloning Backbone Collections

How to override the default implementation of the clone() method of Backbone collections. This demo adds the ability to filter models within the cloning operation.

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

// Backbone Collection reference to use later
var Collection = Backbone.Collection,
    
    // Our base collection
    BaseCollection = Collection.extend({
        
        // Overrides the clone() method and provides
        // a "where" parameter.
        clone: function( where ) {
            
            // Apply the where filter before
            // cloning the collection, if provided.
            if ( where ) {
                return new this.constructor(
                    this.where( where ),
                    { model: this.model,
                      comparator: this.comparator });
            }
            
            // There was no where parameter, so
            // revert back to the default implementation
            // of clone().
            return Collection.prototype.clone
                .call( this );
        }
    }),
    
    // Create a new collection.
    myColl = new BaseCollection([
        { name: 'm1', enabled: true },
        { name: 'm2', enabled: false },
        { name: 'm3', enabled: true },
        { name: 'm4', enabled: false }
    ]);

// Clone "myColl", but only include enabled models.
console.log( myColl.clone( { enabled: true } )
    .toJSON() );