Backbone 101: Collection Fetch Example
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>
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 = [
{
"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/'
});
// 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);
}
});