JSFiddle - React, Tailwind, and code Playground

by John Schulz

HTML

<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>

JavaScript

// Assumes that Backbone.js and Underscore.js are loaded.


var // Dog instances will be added to the Pack application collection
Dog = Backbone.Model.extend({
    initialize: function( data ) {
        this.set( data );
    }
}),

// Pack application
Pack = {

    // Pass this method an array of data objects
    init: function( data ) {

        // Iterate over each object in the data array
        _.each( data, function( dog ) {

            // For each object, create a Dog model instance
            // and add it to the Pack.collection
            Pack.collection.add(

                // Returns new instances of the Dog model
                new Dog( dog )
            );
        });
    },

    // Pack.collection holds instance of Pack.Collection
    collection: null,

    // Create collection
    Collection: Backbone.Collection.extend({
        model: Dog,

        // This is where other dog data will come from
        url: "/dogs/",

        // Custom collection methods

        // Get all dogs in the pack by color
        byColor: function( color ) {

            // Because Backbone collections inherit all of underscore.js
            // collection methods
            // http://documentcloud.github.com/backbone/#Collection-Underscore-Methods
            return this.filter(function( dog ) {
                return dog.get("colors").indexOf( color ) > -1;
            });
        },

        // Get all dogs in the pack by breed
        byBreed: function( breed ) {

            // Normalize to lowercase, allows for case insensitve matching
            breed = breed.toLowerCase();

            return this.filter(function( dog ) {

                var getBreed = dog.get("breed").toLowerCase();

                // case insensitive and will match any word in the breed name
                return getBreed === breed || getBreed.indexOf( breed ) > -1;
            });
        }
    })

    // Here you might add views and a sync loop/poll
};

Pack.collection = new...