Backbone Tutorial

, , …,
Want to master JavaScript in a month? Commit. Buy Xah JavaScript Tutorial. You also get Xah HTML Tutorial and Xah CSS Tutorial.

this page is currently my learning notes of Backbone.js. When this tutorial is mature, this sentence will be removed.

Backbone is a JavaScript library for developing dynamic web sites. Backbone.js is created by Jeremy Ashkenas, who also created CoffeeScript and Underscore.js (Underscore.js is a functional programing JavaScript library.)

What You Need to Know

Note: Backbone is not trivial. You should have a year experience of JavaScript coding for frontend web dev. In particular:

Backbone Dependencies

Download at http://backbonejs.org/. You should get a file named “backbone-min.js”.

Backbone requires:

Backbone is a library, not a framework. You can use it in many ways. Backbone has these objects that are most often used:

The Backbone Object

Use this template to create a HTML page.

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Backbone Sample Template Playing Pad</title>
</head>
<body>

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

<!-- your js stuff here -->

</body>
</html>

Backbone Example Hello World

Open that page in browser. Open your browser's Console. Type “Backbone” Enter ↵. It should output, and you can click on it to see the Backbone object's properties.

Backbone.js object in Google Chrome browser
Google Chrome browser Console, showing the Backbone.js object.

This object named “Backbone” is the entire Backbone library. All Backbone's use is by calling function/methods in the object named Backbone.

Now look at the objects Backbone.Model, Backbone.View, Backbone.Router, Backbone.Collection. These you will be using extensively.

Backbone Example 3

Backbone.Model is a function. The Backbone.Model object is the most important thing in Backbone. It is used to hold all your data.

// creating your own model, use “extend” method
var MyData = Backbone.Model.extend({});
// creating your own model, use “extend” method

// F is your data's constructor. Must start with caps
var F = Backbone.Model.extend(

    // this is your data's default values
    { pp: 3 }

);

// create a object. this is your data object
var v = new F();

console.log(v.pp);              // 3

v.pp = 4;

console.log(v.pp);              // 4

open this page Backbone Example 3. And open your browser console to see its output.

model, get & set properties

use “get” & “set” methods to get/set your model “attributes”. The “attributes” here is like JavaScript's “properties”, but they are not done as properties. (they are, actually implemented as properties of the object model.attributes)

the “escape” method is similar to “get”, but with html escape.

// Example of model's get/set methods for read/write “attributes”

// create a model, with a default property, and init method and a toString method
var B = Backbone.Model.extend( {"pp":0} );

// create a object
var b = new B({"a1":1});

console.log( "b.pp is " + b.pp);   // 0
console.log( "b.a1 is " + b.a1);   // undefined

b.set("a2", 2);

console.log( "b.get('a2') is " + b.get("a2")); // 2

console.log(Object.getOwnPropertyNames(b));

Backbone Example, Model, get & set properties

Backbone model, create class property

you can also create “class properties” by using passing a arg to “Backbone.Model.extend()”. (“Class properties” do not need instantiation.)

// creating class property

var H = Backbone.Model.extend(
    { pp: 1 },
    {pc: "yay class prop"}
);

var h1 = new H();

console.log(h1.pp);

console.log(H.pc);              // invoke class property. no need for instantiation

Backbone Example 4

Model's initialize() method

when creating a constructor from Backbone.Model.extend(o), if o has a method “initialize”, then that will be automatically called when the object is created.

Model's chained inheritance

note that model inherit properties. Example:

// create a model, with a default property, and init method and a toString method
var B = Backbone.Model.extend(
    {pp: 1,
     initialize: function () {console.log("init B");},
     myToString: function () {return JSON.stringify(this.toJSON());},
 }
);

// create a object
var bb = new B({ p1: 1, p2: 2,});

console.log(bb.myToString());

Backbone Example 5

Backbone Model events

models raise events when state changes. Listen for the event named “change” to detect change.

// Example of model's events

// create a model
var cc = new Backbone.Model( {"p1":1, "p2":2} );

// assign a handler on event named "change"
cc.on("change", function () {console.log("wow, changed!"); } );

// change the attribute
cc.set("p1", 3);

// should print “wow, changed!”

Backbone Example, Model, Events

Backbone Complete Example with Model

var Sidebar = Backbone.Model.extend({
  promptColor: function() {
    var cssColor = prompt("Please enter a CSS color:");
    this.set({color: cssColor});
  }
});

window.sidebar = new Sidebar;

sidebar.on('change:color', function(model, color) {
  $('#sidebar').css({background: color});
});

sidebar.set({color: 'white'});

sidebar.promptColor();

Backbone Model, creating custom events

you can create custom events.

to define a custom event, simply assign it a handler, using the “on” method. In the event parameter, just give your event name (a string)

To trigger the event, just call “trigger” method.

// Example of model's events

// create a model
var cc = new Backbone.Model( {"p1":1, "p2":2} );

// assign a handler on event named "change"
cc.on("change", function () {console.log("wow, changed!"); } );

// change the attribute
cc.set("p1", 3);

// should print “wow, changed!”

model's id & cid

each model object has a property named “id” and a property named “cid”

model's default attributes

When you create a model, you can give them default attributes. (so that, it can work sort of as a documentation of your model object)

var Meal = Backbone.Model.extend({
  defaults: {
    "appetizer":  "caesar salad",
    "entree":     "ravioli",
    "dessert":    "cheesecake"
  }
});

alert("Dessert will be " + (new Meal).get('dessert'));

Backbone Example 2

Here's the page Backbone Example 2

Backbone Views

Backbone Tutorial: Views

blog comments powered by Disqus