Backbone.js Sandbox

Backbone.js Sandbox with Backbone, Lodash, jQuery and Handlebars preloaded.

by Ford Heacock

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
<script type="text/template" id="SampleTemplate">
    <h1> Backbone.js Sandbox </h1>
    <table>
        <tr>
            <th>Library</th><th>Version</th>
        </tr>
        {{#each libraries}}
        <tr>
            <td>{{name}}</td><td>{{version}}</td>
        </tr>
        {{/each}}
    </table>
</script>

<div id="LibrariesHolder"></div>

CSS

#LibrariesHolder {
    margin: 12px;
    border-top:  1px solid #ccc;
    border-left: 1px solid #ccc;
    box-shadow: inset 1px 1px 2px 0px #ddd;
    background-color: #eee;
    padding: 12px;
    border-radius: 4px;
}

h1 { margin: 0; text-align: center; }
ul, li { font-size: 12px; }
th, td { text-align: left; width: 100px; }

JavaScript

var LibrariesView = Backbone.View.extend({
    template: Handlebars.compile($('#SampleTemplate').html()),
    initialize: function(options) {
        this.listenTo(options.collection, 'add', this.render);
    },
    serializeData: function () {
        return { libraries: this.collection.toJSON() };
    },
    render: function () {
        var template = this.template,
            data = this.serializeData(),
            html = template(data);

        this.$el.html(html);
    }
});

var c = new Backbone.Collection(),
    v = new LibrariesView({
        el: $('#LibrariesHolder'),
        collection: c
    }),
    libs = [
        {'name': 'jQuery',     'version': jQuery().jquery}, 
        {'name': 'lodash',     'version': _.VERSION}, 
        {'name': 'Backbone',   'version': Backbone.VERSION},
        {'name': 'Handlebars', 'version': Handlebars.VERSION}
    ];
v.render();
_.each(libs, function(lib, index) {
    setTimeout(function() {
        c.add(lib);
    }, (index+1)*250);
});