Backbone 101: Collection Fetch Example

by kyllle

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.2/backbone-min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css">
<h2 class="pg-heading">Backbone Collection fetch example - (check console)</h2>

<p>Fetch the default set of models for this collection from the server, setting them on the collection when they arrive. The options hash takes success and error callbacks which will both be passed (collection, response, options) as arguments. When the model data returns from the server, it uses set to (intelligently) merge the fetched models, unless you pass {reset: true}, in which case the collection will be (efficiently) reset. Delegates to Backbone.sync under the covers for custom persistence strategies and returns a jqXHR. The server handler for fetch requests should return a JSON array of models.</p>

<a href="http://backbonejs.org/#Collection-fetch" target="_blank">Collection Fetch - Backbone Docs</a>

<p>parse is called by Backbone whenever a collection's models are returned by the server, in fetch. The function is passed the raw response object, and should return the array of model attributes to be added to the collection. The default implementation is a no-op, simply passing through the JSON response. Override this if you need to work with a preexisting API, or better namespace your responses.</p>

<a href="http://backbonejs.org/#Collection-parse" target="_blank">Collection Parse - Backbone Docs</a>

CSS

@import url(http://fonts.googleapis.com/css?family=Roboto:300,400,500);

* {
  -webkit-font-smoothing: antialiased;
}

body {
    font-family: Roboto;
    padding: 16px;
    line-height: 1.5;
    font-weight: normal;
    color: #ccc;
    background: #292929;
    font-size: 18px;
}

h1, h2, h3 {
    font-weight: normal;
}

.pg-heading {
    margin-bottom: 0;
}

a {
    color: #95baf6;
    transition: opacity .3s;
}

a:hover {
    opacity: 0.75;
}

JavaScript

console.clear();

var jsonData = {
    "total": 25, 
    "per_page": 10, 
    "page": 2,
    "results": [{
        "id": 1,
        "title": "Pulp Fiction"
    },
    {
        "id": 2,
        "title": "The Usual Suspects"
    }]
}

// Create Model Class
var Model = Backbone.Model.extend();

// Create Collection Class
var Collection = Backbone.Collection.extend({
    
    model: Model,
    
    url: '/echo/json/',
    
    initialize: function() {
        this.on('sync', function(collection, options) {
            console.info('~ Fetch complete `sync` triggered', collection, options);
        });
        
        this.on('add', function(model, collection, options) {
            console.info('~ Fetch complete `add` triggered on each model in collection', model, collection, options);
        });
    },
    
    parse: function(response) {
        console.log('Response before parse', response);
       
        // Access the results array and make this our response
        return response.results;
    }
});


// Instances
var newCollection = new Collection;

newCollection.fetch({
    
    data: {
        json: JSON.stringify(jsonData)
    },
    
    type: 'POST',
    
    success: function(collection, response, options) {
		console.info('~ Response::SUCCESS', collection, response, options);
    },
    
    error: function(collection, response, options) {
        console.info('~ Response::ERROR', collection, response, options);
    }
});