Backbone Application module

by rjzaworski

HTML

<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script id="layout" type="text/template">
<div class="app">
    <div class="form"></div>
    <div class="todos"></div>
</div>
</script>

JavaScript

(function (window) {

    var app = {
        defaults: {
            layout: "#layout"
        },
        init: function (opts) {
            
            var options = _.extend({}, this.defaults, opts);
            var template = $(options.layout).text();
            this.$layout = $(template).appendTo('body');
                        
            for (key in this.data) {
                this.data[key] = new this[key].Collection(this.data[key]);
            }
            
            for (key in this) {
                if (this[key].Router) { 
                    new (this[key].Router); 
                }
            }
            
            Backbone.history.start();
        },
        bootstrap: function (key, val) {
            this.data = this.data || {};
            this.data[key] = val;
        },
        show: function (selector, view) {
            this.$layout.find(selector).empty().append(view.el);
        },
        navigate: function (path) {
            this.trigger('app:navigate', path);
            Backbone.history.navigate(path, { trigger: true });
        }
    };
    
    _.extend(app, Backbone.Events);
    
    window.Application = app;
})(this);

// Bootstrap example
Application.bootstrap('Cars', [
    { make: "Ford", type: "model A" },
    { make: "Ford", type: "model T" }
]);

// Demo module
(function (Application) {
    Application.Cars = {};
    Application.Cars.Model = Backbone.Model.extend({});
    Application.Cars.Collection = Backbone.Collection.extend({
        model: Application.Cars.Model
    });
    Application.Cars.Router = Backbone.Router.extend({
        routes: { '/cars' : 'index' },
        index: function () {
            console.log(carsIndex);
        }
    });
})(Application);

// Fire it up
jQuery(document).ready(function ($) {
    Application.init();
    Application.show('.form', { el: $('<p>Fired up with ' + Application.data.Cars.length + ' cars</p>')});
});