Home > backbone.js, javascript > backbone.js study note [2]

backbone.js study note [2]

Here’s an improved and complete example to the first learning note on backbone.js

<!DOCTYPE html>
    <meta charset="utf-8">
    <title>stock price simple demo</title>
    <div id="data"></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
    <script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>

        var Stock=Backbone.Model.extend({
            defaults: {
                price: 123

        var StockList=Backbone.Collection.extend({
            model: Stock

        var ItemView=Backbone.View.extend({
            tagName: 'li',
            initialize: function() {
                _.bindAll(this, 'render');
                this.model.bind('change:price', this.render);
            render: function() {
                return this;

        var stock1=new Stock({price:333});
        var stock2=new Stock({price:555.667});

        var StockView=Backbone.View.extend({
            el: $('#data'),
            initialize: function() {
                _.bindAll(this, 'render');
                this.collection=new StockList();
            render: function() {
                _(this.collection.models).each( function(item) {
                    var itemview=new ItemView({model:item});
                    $('ul', this.el).append(itemview.render().el);
                }, this);
        var stockview=new StockView();

To test what it does (so far this is the most impressive feature of backbone, the rendering is actually linked directly to the change of model), open a Javascript console (in Chrome or with Firebug in Firefox), and type

stock1.set({ price: 10 })
stock2.set({ price: 999 })

, pay attention to the changes on the page.


Categories: backbone.js, javascript
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: