Backbone Testing Ground

by Julian

HTML

<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone.js"></script>

JavaScript

function logOutput(output) {
    $('body').append("<b>&gt</b> " + output + "<br />");
}
logOutput(new Date());

function delegateEvents(events, from, to, prefix) {
    return from.on(events, function() {
        var args = Array.prototype.slice.apply(arguments);
        if (prefix) {
            var events = args.shift();
            var prefixedEvents = _(events.split(" ")).map(function(event) {
                return prefix + ':' + event;
            }).join(" ");
            args.unshift(prefixedEvents);
        }
        to.trigger.apply(to, args);
    }, to);
}
    
var OuterModel = Backbone.Model.extend({
    initialize: function() {
        this.name = "Outer";
        this.innerModel = new InnerModel();
        delegateEvents('all', this.innerModel, this, 'inner');
        this.innerCollection = new Collection();
        delegateEvents('all', this.innerCollection, this, 'items');
    }
});

var InnerModel = Backbone.Model.extend({
    initialize: function() {
        this.name = "Inner";
    }
});

var Collection = Backbone.Collection.extend({
    model: InnerModel
});

var model = new OuterModel();

model.on('all', function(eventName, obj) {
    logOutput('eventName: ' + eventName + ' for ' + obj.name);
});

model.set("test", "bla");
model.innerModel.set("test", "blub");

model.innerCollection.add({});

var newModel = new InnerModel();
model.innerCollection.add(newModel);
newModel.set('test', 'schubi');
newModel.trigger('lots:of:colons', {name: 'none'});

var deepCollection = new Collection([new InnerModel()]);
newModel.set('deep', deepCollection);
deepCollection.at(0).set('test3', 'dudu');