Testing Filtered Backbone Collections

by Aubrey Taylor

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>

JavaScript

var data, tasks, filterset, filtered, catTasks, catFiltered

data = [{
    'title': 'foo',
    'complete': false
}, {
    'title': 'bar',
    'complete': false
}, {
    'title': 'baz',
    'complete': false
}, {
    'title': 'qux',
    'complete': true
}, {
    'title': 'dog',
    'complete': true
}, {
    'title': 'cat',
    'complete': true
}];

// create a master collection (tasks)
// create a filtered set (filterset)
// create a new collection from filterset (filtered)
tasks     = new Backbone.Collection(data);
filterset = tasks.where({complete: true});
filtered  = new Backbone.Collection(filterset);

// get two references to two models that we know exist in both collections
catTasks    = tasks.findWhere({title: 'cat'});
catFiltered = filtered.findWhere({title: 'cat'});

// log out the current models len for both collections
// the cid for both model refs (should be identical)
// test to see if they are equal (should be true)
console.log('collection model length: ', tasks.models.length, filtered.models.length);
console.log('model cids: ', catTasks.cid, catFiltered.cid);
console.log('models are equal: ', catTasks === catFiltered);

// destroy the filtered model
// this should propagate through both collections
catFiltered.destroy();

// log out that the collection len has changed for both coll.
console.log('collection model length has changed: ', tasks.models.length, filtered.models.length);