Backbone Collection

by gianlucaguarini

HTML

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

JavaScript

// this example show one way to create a backbone collection 
var ModelCollection = Backbone.Collection.extend(),
    // this is the model class that will fill or model collection
    Model = Backbone.Model.extend(),
    //creating a template for our data
    underscoreTemplate = _.template('<li><%= title %><br /><a href="<%= link %>"> <img src="<%= src %>" width="200"></a></li>'),
    // this is our instance to backbone collection
    myModelCollection = new ModelCollection (),
    // static var that point to flickr api
    JSONUrl = 'http://api.flickr.com/services/feeds/groups_pool.gne?id=998875@N22&lang=en-us&format=json&jsoncallback=?';
//first have to load the flickr JSON (you can do that also using fetch() method)
jQuery.getJSON(JSONUrl,function(data){
    // for each item..
    $(data.items).each(function(i,item){
        // ..we create a new model
        var myModel = new Model ({
            title: item.title,
            src: item.media.m,
            link: item.link
        });
        // and push it inside the collection
        myModelCollection.add(myModel);
    });
    // for each model inside our modelCollection we print on page a <li>
    _.each(myModelCollection.models, function(model,i){
        // passing model data inside our underscore template
        $('#result').append(underscoreTemplate(model.toJSON()));
    })
});