Top Banner
Priyanka Wadhwa
22

Backbone.js

Nov 27, 2014

Download

Technology

Basics of Backbone.js with Example Code
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Backbone.js

Priyanka Wadhwa

Page 2: Backbone.js

What is Backbone.js?

It is a lightweight JavaScript library that adds structure to your client-side code (MVC framework).

It is an open-source component of DocumentCloud.

It connects your application to your backend via a RESTful JSON interface, and can automatically fetch and save data.

Backbone.js libraries are used to create single-page applications (SPAs)-changes on the client side without requiring complete page refreshes from the server.

Backbone focuses on giving you helpful methods for querying and manipulating the data.

Small- less of user downloads and no slower connections.

Page 3: Backbone.js

Backbone.js View...

Page 4: Backbone.js

MVC?

Models represent the domain-specific knowledge and data in an application. They can notify observers when their state changes.

Views typically constitute the user interface in an application. They observe models, but don’t directly communicate with them.

Collections handle input (clicks or user actions) and update models.

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.

Page 5: Backbone.js

Why to Consider Backbone.js?

It provides a set of Data-Structuring (models, collections) and user interface (views, URLs) , for building a dynamic application.

Freedom and flexibility to choose from within the prescribed architecture or choose our own.

Changes on the client side without requiring complete page refreshes from the server.

Page 6: Backbone.js

Models

Backbone models contain data for an application as well as the logic around this data.

We can create models by extending Backbone.Model as follows:

Person = Backbone.Model.extend({

initialize: function(){

console.log('hello world');

});

The initialize() method is called when a new instance of a model is created (optional).

var person = new Person ({ name: 'joe' , height: '5 feet'}) ;

console.log(person.get('name'));

Page 7: Backbone.js

Cont...Default values:

defaults:{

name: "Alice",

height:"unknown"

};

var person = new Person();

console.log(person.get('name'));

Model.get()

Get the current value of an attribute from the model.

Model.set()

Model.set() sets a hash containing one or more attributes on the model. When any of these attributes alter the state of the model, a change event is triggered on it.

var person = new Person();

person.set ({name:”joe” , height: “6 feet”});

console.log(person.get ('name'));

Page 8: Backbone.js

Validation. Backbone supports model validation through model.validate() , which allows checking the attribute values for a

model prior to setting them.

var Person = new Backbone.Model({name: 'Jeremy'});

Person.validate = function(attrs) {

if (!attrs.name) {

return 'I need your name';

}

};

Person.set({name: 'Samuel'});

console.log(Person.get('name')); // 'Samuel'

// Remove the name attribute, force validation

Person.unset('name', {validate: true});

* We also make use of the unset() method, which removes an attribute by deleting it

from the internal model attribute’s hash.

Validation functions can be as simple or complex as necessary. If the attributes provided are valid, nothing should be returned from .validate() . If they are invalid, an error value should be returned instead.

Page 9: Backbone.js

Example(Model)...Person = Backbone.Model.extend({initialize: function(){console.log('hello world');this.bind("change:name", function() {console.log(this.get('name') + is now the new name");});this.bind('error' , (function(model, error) {console.log(error);});};defaults:{name: "Alice",height:"unknown"};validate: function (attributes){if (attributes. name == 'bob'){return "your name is bob";}}});

var person = new Person();person.set({name: "bob", height:"5 feet"});console.log(person.toJSON());

Page 10: Backbone.js

View Backbone views are used to reflect what your applications look like. They

are also used to listen to events and react accordingly.

To create a new view, simply extend Backbone.View:

var View = Backbone.View.extend({

TagName: 'li',

events: {

'dblclick label': 'edit',

'keypress .edit': 'updateOnEnter',

'blur .edit':

'close'

},

});

Views in Backbone don’t contain the HTML markup for your application; they contain the logic behind the presentation of the model’s data to the user.

Page 11: Backbone.js

A view’s render() method can be bound to a model’s change() event, enabling the view to instantly

reflect model changes without requiring a full page refresh.

In other words, renders the view template from model data, and updates this.el with the new HTML.

<script type="text/template" id="search_template">

<input type="text" id="search_input" />

<input type="button" id="search_button" value="Search" />

</script>

<div id="search_container"></div>

<script type="text/javascript">

SearchView = Backbone.View.extend({

initialize: function(){

this.render();

},

render: function(){

var template = _.template( $("#search_template").html(), {} ); // Compile the template using underscore

this.$el.html( template ); // Load the compiled HTML into the Backbone "el"

}

});

var search_view = new SearchView({ el: $("#search_container") });

</script>

Page 12: Backbone.js

el? el is a reference to a DOM element, and all views must have one. Views can use el to compose

their element’s content and then insert it into the DOM all at once, which makes for faster rendering because the browser performs the minimum required number of reflows.

// defining a pre-existing DOM element where we want to show the view.

<div id=”container”>

<button>Load</button>

<ul id=”list”></ul>

</div>

Var View= Backbone.View.extend({

Initialize: function() {

console.log(“view”)

}

});

var view = new View({ el: $('#container')});

Or

el: '#footer'

Page 13: Backbone.js

Cont...

//creating a new DOM element

var view = new View ({ tagName , className , id , attributes })

Or

var TodosView = Backbone.View.extend({

tagName: 'ul',

className: 'container',

id: 'todos',

});

var todosView = new TodosView();

console.log(todosView.el);

Page 14: Backbone.js

Example(View)...<div id="container">

<button>Load</button>

<ul id="list"></ul>

</div>

<div id="list-template">

<li><a href=""></a></li>

</div>

model = new Backbone.model ({

data : [

{text : "Google", href: "http://google.com"},

{text : "Facebook", href: "http://facebook.com"},

{text : "YouTube", href: "http://youtube.com"},

]

)};

var View = Backbone.View.extend({

initialize : function() {

this.template = $('#list-template').children();

};

el : '#container',

events : { // Listening for events

"click button" : "render"

},

render: function() {

var data = this.model.get('data');

for(var i=0, l=data.length; i<l; i++){

var li = this.template.clone().find('a').attr('href' , data[i].href).text(data[i].text).end();

this.$el.find('ul').append(li);

} } });

var view = new View({model : model });

Page 15: Backbone.js

Collections

Collections are sets of models. They define a property specifying the type of model that it will contain, along with any instance properties.

We create them by extending Backbone.Collection .

var Todo = Backbone.Model.extend({

defaults: {

title: '',

completed: false

}

});

var TodosCollection = Backbone.Collection.extend({

model: Todo

});

var myTodo = new Todo({title:'Read the whole book', id: 2});

// pass array of models on collection instantiation

var todos = new TodosCollection([myTodo]);

console.log("Collection size: " + todos.length); // Collection size: 1

Page 16: Backbone.js

add() and remove() models through collections...var Todo = Backbone.Model.extend({defaults: {title: '',completed: false}});var TodosCollection = Backbone.Collection.extend({model: Todo,});var a = new Todo({ title: 'Go to Jamaica.'}),b = new Todo({ title: 'Go to China.'}),c = new Todo({ title: 'Go to Disneyland.'});var todos = new TodosCollection([a,b]);console.log("Collection size: " + todos.length);// Logs: Collection size: 2todos.add(c);console.log("Collection size: " + todos.length);// Logs: Collection size: 3todos.remove([a,b]);console.log("Collection size: " + todos.length);// Logs: Collection size: 1todos.remove(c);console.log("Collection size: " + todos.length);// Logs: Collection size: 0

Page 17: Backbone.js

Some events used in collections..

Reset() : people.reset([{ name : “bob”}, { name : “jim”}])

Events:

On - people.on ('remove' , function () { }) Get - people.get(2) At - people.at (index) Push - people.push( ) Pop - people.pop( ) Sort - people.sort( ) Pluck - people.pluck('name') Where - people.where({name : “joe”}));

Page 18: Backbone.js

Events

on() :- Bind a callback function to an object.

off() :- Remove a previously-bound callback function from an object.

trigger() :-Trigger callbacks for the given event.

ourObject.on('dance', function(msg){

console.log('We triggered ' + msg);

});

// Trigger the custom event

ourObject.trigger('dance', 'our event');

ourObject.off('dance');

Page 19: Backbone.js

Cont...

ListenTo():-Tell an object to listen to a particular event on an other 0bject. StopListening():- Tell an object to stop listening to events.

a.listenTo(b, 'anything', function(event){console.log("anything happened"); });a.listenTo(c, 'everything', function(event){console.log("everything happened"); });// trigger an eventb.trigger('anything'); // logs: anything happened// stop listeninga.stopListening();// A does not receive these eventsb.trigger('anything');c.trigger('everything');

Page 20: Backbone.js

Limitations of Backbone.JS

1. Backbone lacks support for two-way data binding, meaning you will have to write a lot of boilerplate to update the view whenever your model changes, and to update your model whenever the view changes.

2. Views in Backbone manipulate the DOM directly, making them really hard to unit-test, more fragile and less reusable.

3. Changing a CSS class name, adding a new element with the same class name or even wrapping some DOM tree inside another element can break your CSS selectors and render your app usable.

Page 21: Backbone.js

Dependencies

Backbone's only hard dependency is Underscore.js (open-source component of DocumentCloud).

3 scripts required to be imported to run the previous examples are:

1.<script src="http://documentcloud.github.com/underscore/underscore.js"></script>

2.<script src="http://documentcloud.github.com/backbone/backbone.js"></script>

3.<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>

Page 22: Backbone.js