Backbonejs Hello World
learn backbonejs
by erick
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
<h1><b>Learn How to use Backbone JS</b></h1>
<hr>
<hr>
<hr>
JavaScript
(function($){
var ListView = Backbone.View.extend({
el: $('body'), // attaches `this.el` to an existing element.
events: {
'click button#add': 'addItem'
},
initialize: function(){
_.bindAll(this, 'render', 'addItem');
// fixes loss of context for 'this' within methods
// every function that uses 'this' as the current object should be in here
this.counter = 0; // total number of items added thus far
this.render(); // not all views are self-rendering. This one is.
},
render: function(){
$(this.el).append("<button id='add'>Add list item</button>");
$(this.el).append("<ul></ul>");
},
addItem: function(){
this.counter++;
$('ul', this.el).append("<li>hello world"+this.counter+"</li>");
}
});
var listView = new ListView();
})(jQuery);
//Note: render() now introduces a button to add a new list item.
// initialize(): Automatically called upon instantiation. Where you make all types of bindings, excluding UI events, such as clicks, etc.