Backbone.js – Developing Backbone.js Applications – Models



Backbone.js – Developing Backbone.js Applications – Models

0 2


backboneRails_Presentation


On Github lporras / backboneRails_Presentation

Backbone.js

Developing Backbone.js Applications

Created by Luis Porras / @lporras16 Node.js developer at Selfie

Give your JS App some Backbone with Models, Views, Collections, and Routers
Get yor truth out of the DOM @jashkenas

Simple small library

Development Version (1.1.2) 60kb, Full source, lots of comments Production Version (1.1.2) 6.5kb, Packed and gzipped

Open Source

Ligthweight

  • Easy to read in an hour or two
  • Focused on functionality
  • No UI widgets
  • Template agnostic
  • Use the HTML & CSS you already know

Dependencies

Hard dependency:

Underscore or Lo-Dash

DOM Manipulation:

Either jQuery or Zepto

JSON Parse/Serialize (Just for Old Browsers)

Json2.js

Why should you consider using Backbone.js?

You should consider it whether You:

  • want something flexible
  • need a persistence layer and RESTful sync
  • want an event-driven communication
  • are thinking of using templating and routing
  • would like decisions about the architecture left up to you

Models

  • Store data
  • Provide get/set accessors
  • Fire events when modified
  • Optionally make REST calls to a server for persistence

Define a Class

//Define a Model Class
var TodoItem = Backbone.Model.extend({
  urlRoot: "/todos",
  defaults:{
    description: 'Empty todo...',
    status:      'incomplete'
  }
});
            

Get/Set Attributes

//To Create a model instance
var todoItem = new TodoItem({
  description: "attend the lesson",
  status: "incomplete",
  id: 1
});

//To get an attribute
todoItem.get('description');

//To set and attribute
todoItem.set({status: 'complete'});
            

Sync with API

var todoItem = new TodoItem();
todoItem.set({description: 'Learn Backbone'});
todoItem.save();
//POST /todos 'todos#create'

var todoItem = new TodoItem({id: 1})
todoItem.fetch();
//GET /todos/1 'todos#show'

todoItem.set({description: "I should clean up my room"})
todoItem.save();
//PUT /todos/1 'todos#update'

todoItem.destroy();
//DELETE /todos/1 'todos#destroy'
            

Built-in Events

//Bind model events
todoItem.on('change', doThing);

//Event triggerd on change
todoItem.set({description: 'Pay all beers tonight'});

//set without triggering event
todoItem.set({description: 'I changed my mind, no beers tonight', {silent: true}});
            

Collections

Backbone.Collection

  • Fecth model Data
  • Add to existing set
  • Remove from set
  • Your custom query code
  • Provide useful suite of underscore.js methods

Define a Collection

var TodoList = Backbone.Collection.extend({
  model: TodoItem
});
var todoList = new TodoList();
            

Getting Data from Server

Collection Events

Underscore Methods

Ordered Collections

//If you define a comparator, it will be used to mantain the collection in sorted order
var Chapter = Backbone.Model.extend({});
var Chapters = Backbone.Collection.extend({
  model: Chapter,
  comparator: function(chapter){
    return chapter.get("page");
  }
});

var chapters = new Chapters([]);
chapters.add(new Chapter({page: 9, title: "The End"}));
chapters.add(new Chapter({page: 5, title: "The Middle"}));
chapters.add(new Chapter({page: 1, title: "The Beginning"}));

console.log(chapters.pluck('title'));
//=> "The Beginning, The Middle, The End"
            

Next Round: Views

Views

  • Display data & UI controls
  • Render data with a template
  • React to model changes
  • Act on user input

Define View

var TodoView = Backbone.View.extend({
  tagName   : 'article', //create tag article
  id        : 'todo-view', //with id 'todo-item
  className : 'todo', //and class todo

  //template to use
  template: _.template( $('#item-template').html() ),

  //Listening to DOM events on the view
  events: {
    'change input': 'toggleStatus'
  },

  //Every Backbone Class has a constructor method
  initialize: function(options){
    this.model.on('change', this.render, this);
    this.model.on('destroy', this.remove, this);
  },

  //override this method if the view generates a new DOM Object
  render: function(){
    return this.$el.html(this.template(this.model.toJSON()));
    return this;
  },

  toggleStatus: function(){
    this.model.toggleStatus();
  },

  //this method delete the view from the DOM
  remove: function(){
    ...
  }
});
            

Template Engines

DOM Events

If you are using JQuery:

Routing

Routes

  • Map url fragments
  • Hash fragments
  • PushState (optional)

Define Routes

more routes

PushState

Examples

DocumentCloud

USA Today

Foursquare

and much more ...

Some Useful Resources

Thanks