Backbone Template

Standard fiddle

by Simon Dion

HTML

<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
<div id="container">a</div>

JavaScript

SelfRemovableView = Backbone.View.extend({
    events: {
        'click .remove':'remove'
    },
    render: function(){
         this.$el.html(this.template());   
        return this;
    }
});
BaloonView = SelfRemovableView.extend({
    template: _.template('<h2>Baloon <button class="remove">X</button></h2>')
})
SquareView = SelfRemovableView.extend({
    template: _.template('<h2>I\'m a square <button class="remove">X</button></h2>')
});

// simple backbone view (not extended)
SimpleView = new Backbone.View({
    template : _.template('<h2>Simple view. <small>Click on me I will disapear</small></h2>'),
    events: {
        'click': 'remove',   
    },
     render: function(){
         this.$el.html(this.template());   
         return this;
    }
});
// extended views
var view1 = new BaloonView();
var view2 = new BaloonView();
var view3 = new SquareView();
var view4 = new SquareView();

var container = {
    root : $('#container'),
    elements : null,
    add: function(view){
        console.log(this.root);
        this.root.append(view.render().el);
        console.log(view.el);
        this.elements = this.elements || [];
        this.elements.push(view.el);
    },
    onItemRemoved: function(view_orviewelement_orviewcid){
        console.log('A view in this container as been removed!');
    }
}
container.add(SimpleView);
container.add(view1);
container.add(view2);
container.add(view3);
container.add(view4);