All notes
Backb

JST

Backbone.js uses the templating engine of Underscore.js since Backbone has a hard dependency on Underscore. 9bitStudios.com: using templates in backboneJS.

underscoreJS.org: template.

Execute arbitrary JavaScript code, with <% … %>.
To interpolate values, using <%= … %>.
If you wish to interpolate a value, and have it be HTML-escaped, use <%- … %>.


var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'});
// "hello: moe"

var template = _.template("<b><%- value %></b>");
template({value: '<script>'});
// "<b>&lt;script&gt;</b>"

// You can also use print from within JavaScript code. This is sometimes more convenient than using <%= ... %>.
var compiled = _.template("<% print('Hello ' + epithet); %>");
compiled({epithet: "stooge"});
// "Hello stooge"

Events

Full list

Backbone's DOM event for Views come from jQuery or ZeptoJS (whichever one you are using). Any valid event from either of those libraries, is a valid event in a Backbone view.

on(), trigger()



var object = {};
_.extend(object, Backbone.Events);
object.on("kick", function() {
  alert("Ouch, you just kick me");
});
object.trigger("kick");

listenTo()



//if you put this code inside a view, the view will now listening to its model change event
this.listenTo(this.model, ‘change’, this.doChange);

Events on Model

mrbool.co.



var ImageModel = Backbone.Model.extend({
  initialize: function() {
    this.on('change',this.someChange,this); //when some property in this object has changed, run this.someChange().
    },
  defaults: {
    title : 'untitled',
    description : 'no description available',
    owner : 'anonymous',
    date : 'no date supplied'
  },
  someChange: function(model,options) {
    alert(‘something has changed’);
  }
});

var photo = new ImageModel({title:’awesome image’}); //create new instance
photo.set(‘title’,’really awesome indeed’); //change the title attribute, this will trigger ‘change’event
photo.set({title:’well i agree’},{agree: ‘yep’}); //alternative way to change model attribute with optional option passed, this will also trigger change event.

Events on Collection



//first create a model
var ImageModel = Backbone.Model.extend({
  defaults: {
    title : ‘untitled’,
    description : ‘no description available’,
    owner: ‘Muhammad Azamuddin’,
    date: ’29 March 2013’
  }
});

var GalleryCollection = Backbone.Collection.extend({
  model : ImageModel,
  initialize : function () {
    this.on(‘add’,this.newComer,this);
    this.on(‘change’,this.someChange,this);
  },
  newComer : function (model) { alert(‘welcome ’+ model.get(‘title’); },
  someChange: function() { alert(‘model has changed’); }
});

//create a new gallery
var imageGallery = new GalleryCollection();
//trigger the events
var pic = {title:’new awesome pic’});
imageGallery.add(pic); //this will trigger add event on our collection
pic.set(‘title’,’awesome and beautiful pic’); //will trigger change events on our collection

Functions

bind, bindAll

bigBinary.com: bind and bindALl in backbone.



##### Why apply is needed

var func = function beautiful(){
  alert(this + ' is beautiful');
};
func(); // [object window] is beautiful
func.apply('Internet'); // Internet is beautiful

function Developer(skill) {
  this.skill = skill;
  this.says = function(){
    alert(this.skill + ' rocks!');
  }
}
var john = new Developer('Ruby');
john.says(); // Ruby rocks!
var func = john.says;
func();// undefined rocks!
func.apply(john); // Ruby rocks!

##### bind, bindAll

# bind internally uses apply to set this to the second parameter we passed while invoking bind.
# Notice that bind does not change existing function. It returns a new function and that new function should be used.
var func = _.bind(john.says, john);
func();// Ruby rocks!

# bindAll internally calls bind and it overrides the existing attribute with the function returned by bind.
# So in bindAll we do not have to worry about the returned value.
_.bindAll(john, 'says');
var func = john.says;
func(); //Ruby rocks!

Color functions

#----------rgb

rgb($red, $green, $blue) : Creates a Color from red, green, and blue values.
rgba($red, $green, $blue, $alpha) : Creates a Color from red, green, blue, and alpha values.

red($color) : Gets the red component of a color.
green($color) : Gets the green component of a color.
blue($color) : Gets the blue component of a color.

mix($color1, $color2, [$weight]) : Mixes two colors together.

#---------- HSL Functions

hsl($hue, $saturation, $lightness) : Creates a Color from hue, saturation, and lightness values.
hsla($hue, $saturation, $lightness, $alpha) : Creates a Color from hue, saturation, lightness, and alpha values.

hue($color) : Gets the hue component of a color.
saturation($color) : Gets the saturation component of a color.
lightness($color) : Gets the lightness component of a color.

adjust-hue($color, $degrees) : Changes the hue of a color.

lighten($color, $amount) : Makes a color lighter.
darken($color, $amount) : Makes a color darker.

saturate($color, $amount) : Makes a color more saturated.
desaturate($color, $amount) : Makes a color less saturated.

grayscale($color) : Converts a color to grayscale.

complement($color) : Returns the complement of a color.

invert($color, [$weight]) : Returns the inverse of a color.

#---------- Opacity Functions

alpha($color) / opacity($color) : Gets the alpha component (opacity) of a color.

rgba($color, $alpha) : Changes the alpha component for a color.

opacify($color, $amount) / fade-in($color, $amount) : Makes a color more opaque.

transparentize($color, $amount) / fade-out($color, $amount) : Makes a color more transparent.

#---------- Other Color Functions

adjust-color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha]) : Increases or decreases one or more components of a color.

scale-color($color, [$red], [$green], [$blue], [$saturation], [$lightness], [$alpha]) : Fluidly scales one or more properties of a color.

change-color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha]) : Changes one or more properties of a color.

ie-hex-str($color) : Converts a color into the format understood by IE filters.

List Functions

Lists in Sass are immutable; all list functions return a new list rather than updating the existing list in-place.

All list functions work for maps as well, treating them as lists of pairs.

length($list) : Returns the length of a list.

nth($list, $n) : Returns a specific item in a list.

set-nth($list, $n, $value) : Replaces the nth item in a list.

join($list1, $list2, [$separator, $bracketed]) : Joins together two lists into one.

append($list1, $val, [$separator]) : Appends a single value onto the end of a list.

zip($lists…) : Combines several lists into a single multidimensional list.

index($list, $value) : Returns the position of a value within a list.

list-separator($list) : Returns the separator of a list.

is-bracketed($list) : Returns whether a list has square brackets.

Other functions

#---------- Miscellaneous Functions

if($condition, $if-true, $if-false) : Returns one of two values, depending on whether or not `$condition` is true.

unique-id() : Returns a unique CSS identifier.

Model

constructor, initialize



view.tempModel.id
// "fd2bac723dd3610d16b16ab62be3675e"

// Then you can use the id to retrieve the model:
var existingModel = new Backbone.Model({id:"fd2bac723dd3610d16b16ab62be3675e"});
existingModel.fetch();

urlRoot, url

SO: backboneJS models and collection url's.



var Book = Backbone.Model.extend({urlRoot: 'books' });
var book = new Book({id: 1});
book.fetch();  // will get /books/1

var Book = Backbone.Model.extend({});
var book = new Book({url: 'books/1'});
book.fetch();  // will get /books/1


var Books = Backbone.Collection.extend({model: Book});
var books = new Books({ /*....*/ });
books.fetch(); // will get /books/ 

toJSON()

The toJSON() method just returns a shallow clone of the model's attributes property.

SO. From the annotated Backbone.js source:


toJSON: function(options) {
  return _.clone(this.attributes);
}

Collection

Collections are ordered sets of models.

You can bind "change" events to be notified when any model in the collection has been modified, listen for "add" and "remove" events, fetch the collection from the server.

Any event that is triggered on a model in a collection will also be triggered on the collection directly, for convenience. This allows you to listen for changes to specific attributes in any model in a collection, for example: documents.on("change:selected", ...).

extende()


Backbone.Collection.extend(properties, [classProperties])
// Provides instance properties, as well as optional classProperties to be attached directly to the collection's constructor function.

model, models



var Library = Backbone.Collection.extend({
  model: Book
});

// A collection can also contain polymorphic models by overriding this property with a constructor that returns a model.
var Library = Backbone.Collection.extend({
  model: function(attrs, options) {
    if (condition) {
      return new PublicDocument(attrs, options);
    } else {
      return new PrivateDocument(attrs, options);
    }
  }
});

//---------- models

// Raw access to the JavaScript array of models inside of the collection. Usually you'll want to use get, at, or the Underscore methods to access model objects, but occasionally a direct reference to the array is desired.

modelId



var Library = Backbone.Collection.extend({
  // Override this method to return the value the collection will use to identify a model given its attributes.
  modelId: function(attrs) {
    return attrs.type + attrs.id;
  }
});

var library = new Library([
  {type: 'dvd', id: 1},
  {type: 'vhs', id: 1}
]);

var dvdId = library.get('dvd1').id;
var vhsId = library.get('vhs1').id;
alert('dvd: ' + dvdId + ', vhs: ' + vhsId);

constructor / initialize



Backbone.Collection([models], [options])
// There are a couple of options that, if provided, are attached to the collection directly: "model" and "comparator". Passing false as the comparator option will prevent sorting.

// Pass in the initial array of models.
var tabs = new TabSet([tab1, tab2, tab3]);

// Pass null for models to create an empty Collection.
var spaces = new Backbone.Collection(null, {
  model: Space
});

View

extend()

You can use it to override the render function, specify your declarative events, and perhaps the tagName, className, or id of the View's root element.



// Backbone.View.extend(properties, [classProperties])

var DocumentRow = Backbone.View.extend({
  tagName: "li",
  className: "document-row",
  events: {
    "click .icon":          "open",
    "click .button.edit":   "openEditDialog",
    "click .button.delete": "destroy"
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
  },

  beforeRender: function() {
    console.log('beforeRender');
  },

  render: function() {
    ...
  },

  afterRender: function() {
    console.log('afterRender');
  }
});

constructor / initialize

There are several special options that, if passed, will be attached directly to the view: model, collection, el, id, className, tagName, attributes and events.

If you'd like to create a view that references an element already in the DOM, pass in the element as an option: new View({el: existingElement}).



var doc = documents.first();

new DocumentRow({
  model: doc,
  id: "document-row-" + doc.id
});

el, \$el

SO.



// Look at the view's _setElement function from the Backbone's codes:
_setElement: function(el) {
  this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
  this.el = this.$el[0];
},
// This ensures that el is always a DOM element, and that $el is always a jQuery object of it.

// So the following is valid even though I used a jQuery object as the el option or property:
var myView = new Backbone.View({ el: $('.selector') });
// or
var MyView = Backbone.View.extend({
  el:  $('.selector')
});

model

Example: how to set the view's model

bardev.com.

In the following example the view will be updated when the model changes:



<html >
<head>
  <title></title>
  <script src="/scripts/jquery-1.8.3.js" type="text/javascript"></script>
 	<script src="/scripts/underscore.js" type="text/javascript"></script>
	<script src="/scripts/backbone.js" type="text/javascript"></script>
</head>
<body>
  <div id="container-movie"></div>
  
  <script type="text/template" id="template-movie">
    Title: <%=title%>;
    Rating: <%=mpaaRating%>
  </script> 

  <script type="text/javascript">
    var Movie = Backbone.Model.extend({});

    var MovieView = Backbone.View.extend({
      el: "#container-movie",
      template: _.template($("#template-movie").html()),
      initialize: function() {
        this.model.on("change", this.render);
      },
      render: function() {
        console.log("MovieView render; Movie Title: " + this.model.get("title"));
        var htmlOutput = this.template(this.model.toJSON());
        this.$el.html(htmlOutput);
        return this;
      }
    })

    var movie = new Movie({ title: "The Lion King", mpaaRating: "R" });
    var movieView = new MovieView({ model: movie }); <!-- Here is where model is bound to view. -->
    movie.set({ title: "Titanic" });
    movie.set({ title: "The Godfather" });
  </script>
</body>
</html>

<!-- Output:
MovieView render; Movie Title: Titanic
MovieView render; Movie Title: The Godfather
-->

events

Format: {"event selector": "callback"}. The callback may be either the name of a method on the view, or a direct function body. Omitting the "selector" causes the event to be bound to the view's root element (this.el).

extend

Backbone.View.extend(properties, [classProperties])
Optional "classProperties" is to be attached directly to the constructor function.


var DocumentRow = Backbone.View.extend({

  tagName: "li",
  className: "document-row",

  events: {
    "click .icon":          "open",
    "click .button.edit":   "openEditDialog",
    "click .button.delete": "destroy"
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
  },
  render: function() {
    ...
  }
});
// Properties like tagName, id, className, el, and "events" may also be defined as a function, if you want to wait to define them until runtime.

options

SO: how to pass params to a view.

As of backbone 1.1.0, the options argument is no longer attached automatically to the view.

So in your initialize method, you can save the options passed as this.options:



initialize: function(options) {
  this.options = options;
  _.bindAll(this, 'render');
}

new MenuView({
  collection: itemColl,
  position: this.getPosition()
})
// And then, in MenuView, you can use this.options.position.

Options is deprecated

backbonejs.org: changelog.

Backbone Views no longer automatically attach options passed to the constructor as this.options and Backbone Models no longer attach url and urlRoot options, but you can do it yourself if you prefer.

options in JS

"options", conventionally, is a javascript object of key/value pairs that provide data/context/arguments/configuration to a method call.

so: what is options in backbone.js.


var makePerson = function(name, options) {
  var person = {};
  person.name = name;
  person.age  = options.age;
  return person;
};

var me = makePerson('Alex', {age:30});

FAQ

What is my Backbone version

SO: what is my backbone version.

Type Backbone.VERSION in the devtools console.