backbone.initialize


Backbone notes

When you work with JS in complicated apps it's easy to get yourself into a mess of selectors, events, callbacks, functions and more. There is when frameworks like Backbone come to rescue us from that anarchy. Backbone give us a way to decouple things and give a structure(MVC) to our JS application.

"With Backbone, you represent your data as Models, which can be created, validated, destroyed, and saved to the server. Whenever a UI action causes an attribute of a model to change, the model triggers a "change" event; all the Views that display the model's state can be notified of the change, so that they are able to respond accordingly, re-rendering themselves with the new information. In a finished Backbone app, you don't have to write the glue code that looks into the DOM to find an element with a specific id, and update the HTML manually — when the model changes, the views simply update themselves."

Models / http://backbonejs.org/#Model


Contains the interactive data as well as large part do the logic surrounding it: conversions, validations, computed properties, and access control.

Simple model


  var Person = Backbone.Model.extend();



Instance of Person model


  var person = new Person({name: "Tony"});



Set attributes to the person


  person.set({lastname: "Montana",age: 34});



Get person attribute age


  person.get("age");



Set default values at the model


  Person = Backbone.Model.extend({
    defaults: {
      name: 'Fetus',
      age: 0,
      children: []
    },
  });



Set an initialize function (constructor)


  Person = Backbone.Model.extend({
    defaults: {
      name: 'Fetus',
      age: 0,
      children: ["Paul", "Ringo"]
    },
    initialize: function(){
      this.set("number_of_childrens", this.get("children").length);
      this.on("change:name", function(){
        alert("Changed my name to " + name );
      });
    }
  });



Work with RESTful service

To work with a restful service you need to set the urlRoot to the restful service url this will allow us to perform fetch, save and destroy actions on our model instance.


  Person = Backbone.model.extend({
    urlRoot: '/persons'
  });


The method fetch will fetch the person with the seted id(1 in this example), making a request by GET to /persons/1


  person = new Person({id: 1});
  person.fetch();


Update the person making a request by PUT to /persons/1 with JSON params


  person.set({name: 'Bill'});
  person.save(); 


Save newPerson making a request by POST to /persons with JSON params


  newPerson = new Person();
  newPerson.set({name: "Carol", age: 24});
  newPerson.save(); 


Destroy newPerson making a request by DELETE to /persons/2


  newPerson.get("id"); // => 2
  newPerson.destroy();



Model events

On the initialize function you can bind(using bind/on) events, the example bind changes:childrens on children attribute and update the number of children's.

 
  Person = Backbone.Model.extend({
    defaults: {
      name: 'Fetus',
      age: 0,
      childrens: []
    },
    initialize: function(){
      this.set("number_of_childrens", this.get("childrens").length);
      this.on("change:childrens", function(){
        this.set("number_of_childrens", this.get("childrens").length);
      });
    }
  });

  var person = new Person();
  person.get("number_of_childrens"); #=> 0
  person.set("childrens", ["Paul", "Ringo"]);
  person.get("number_of_childrens"); #=> 2



Validation


  Person = Backbone.Model.extend({
    validate: function(attributes){
      if(attributes.age < 0){
        //When you return a string from the validate, backbone throw an error
        return "Age must can't be negative";
      }
    },
    initialize: function(){
      this.on("error", function(model, error){
        alert(error);
      });
    }
  });



Views / http://backbonejs.org/#View


"Backbone views are almost more convention than they are code — they don't determine anything about your HTML or CSS for you, and can be used with any JavaScript templating library. The general idea is to organize your interface into logical views, backed by models, each of which can be updated independently when the model changes, without having to redraw the page. Instead of digging into a JSON object, looking up an element in the DOM, and updating the HTML by hand, you can bind your view's render function to the model's "change" event — and now everywhere that model data is displayed in the UI, it is always immediately up to date."


  var AppointmentView = Backbone.View.extend({
    initialize: function(){
      this.model.on('change', this.render, this);
      this.model.on('destroy', this.remove, this);
    },
    tagName: "li",
    className: "document-row",
    template: _.template('<%= title %> x'),
    events:  { "click a": "cancel" },
    cancel: function(){
      this.model.cancel();
    },
    render: function(){
      this.$el.html(this.template(this.model.toJSON()));
      return this;
    },
    remove: function(){
      this.$el.remove();
    }
  });


initialize
Is the contructor of the view, among other things you can bind events on the model that is related to the view. In the example we bind the event change and destroy on the model.

tagName
Specifies the HTML tag that will surround the View, by the default is 'div'

className
Set a class to the surrounding tag

template
Set the html template for the view, in this example we use
Undersocre.js http://documentcloud.github.com/underscore/#template

events
Bind DOM events on the view. In the example we bind the event click on "a" to trigger the method cancel.

this.el
this.el represent the DOM object of the view, whether is has been inserted into the page or not.
this.$el is an shortcut of $(this.el) for JQuery or Zepto

render
Is the responsable to render the view template from model data and updates the this.el



Collections / http://backbonejs.org/#Collection


"Collections are ordered sets of models. You can bind "change" event to be notified when any model in the collection has been modified, listen for "add" and "remove" events, fetch the collection from the server, and use a full suite of Underscore.js methods."

Here is a generic Model/Collection example


  var Person = Backbone.Model.extend({});

  var PersonList = Backbone.Collection.extend({
    model: Person
  });



Fetch data into the collection


  var Person = Backbone.Model.extend({
    defaults: {
    name: "Adam",
      age: 29
    }
  });

  var PersonList = Backbone.Collection.extend({
    model: Person
  });

  var person1 =  new Person();

  var person2 =  new Person(name: "Mark");

  var myGroup = new PersonList([person1, person2]);



Fetch data from RESTful service

To do it, when we define the collection we also set the "url" with the url of our restful server.


  var Person = Backbone.Model.extend({});

  var PersonList = Backbone.Collection.extend({
    url: '/persons',
    model: Person
  });

  var persons = new PersonList({});



Calling the method fetch will load all the persons that or restful service return to us.


  persons.fetch(); // GET /todos



Routers / http://backbonejs.org/#Router


"Web applications often provide linkable, bookmarkable, shareable URLs for important locations in the app. Until recently, hash fragments (#page) were used to provide these permalinks, but with the arrival of the History API, it's now possible to use standard URLs (/page). Backbone. Router provides methods for routing client-side pages, and connecting them to actions and events. For browsers which don't yet support the History API, the Router handles graceful fallback and transparent translation to the fragment version of the URL."

To work with routes you need to start history and set the initial url, you can work with hasbangs or pushstate urls, hasbangs is the default.

Hasbangs


  Backbone.history.start(); #pushState off 
  router.navigate("todos/1") => www.mySite#todos/1


Pushstate

    
  Backbone.history.start({pushState: true}); #pushState on  
  router.navigate("todos/1") => www.mySite/todos/1


Here is a example of a route, the function routes is the one who set the urls and the corresponding actions, in the example "" url will call the index action and "todos/:id" will call the show action and will send a parameter.


  window.TodoApp = new (Backbone.Router.extend({
    routes: {
      "": "index",
      "todos/:id": "show"
    },
    index: function(){
      ...
    },
    show: function(id){
      ...
    }
  }));



References



By Pablo Monfort



How to contact us

Our Location

DireccionArismendi 1420 Of. 102 Telefono(+598) 2409 15 66 Mailinfo@vairix.com

Follow us


Want to contact us?