Backbone.js views with callback

A simple exemple of BackBone.JS views with callback. A many use-cases can be imagined with that.

by Atinux

HTML

<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script src="https://raw.github.com/derickbailey/backbone.modelbinding/master/backbone.modelbinding.min.js"></script>
<script src="https://raw.github.com/derickbailey/backbone.memento/master/backbone.memento.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
<div id="content"></div>

CSS

#content {
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -o-user-select: none;
    user-select: none;
}
.carre {
    width:200px;
    height:120px;
    border:1px grey solid;
    position:absolute;
    left:10;
    top:10;
    text-align:center;
    padding-top:80px;
    cursor:pointer;
    border-radius:15px;
}

JavaScript

var app = {
    models: {},
    views: {},
    init: function() {
        var view = new app.views.Carre({
            renderTo: $('#content')
        });
    }
};

app.views.Carre = Backbone.View.extend({
    tagName: 'div',
    className: 'carre',
    initialize: function(hash) {
        _.bindAll(this, 'onDone');
        this.renderTo = hash.renderTo || $('body');
        this.el = $(this.el);
        this.render();
    },
    events: {
        'click': 'addChild'
    },
    render: function() {
        this.el.text('Click me');
        this.renderTo.html(this.el);
    },
    addChild: function() {
        var view = new app.views.CarreChild({
            el: this.el,
            callbackDone: this.onDone
        });
    },
    onDone: function(view) {
        this.el.css({
            'backgroundColor': view.myEl.css('backgroundColor')
        });
        view.remove();
    }
});

app.views.CarreChild = Backbone.View.extend({
    initialize: function(hash) {
        this.callbackDone = hash.callbackDone ||
        function() {};
        this.render();
    },
    render: function() {
        var c = this.myEl = $('<div>', {
            'class': 'carre',
            'css': {
                'backgroundColor': 'rgb(' + this.nbAl() + ', ' + this.nbAl() + ', ' + this.nbAl() + ')'
            }
        });
        c.appendTo(this.el);
        var that = this;
        c.animate({
            left: 50,
            top: 300,
            opacity: 0.6
        }, 500, function() {
            c.animate({
                left: 350,
                top: 50,
                opacity: 0
            }, 500, function() {
                that.callbackDone(that);
            });
        });
    },
    nbAl: function() {
        return Math.round(Math.random() * 200);
    },
    remove: function() {
        this.myEl.remove();
    }
});

$(document).ready(app.init);