Backbonejs

16
Backbone.js Ankit Shukla Email: [email protected]

description

It has the brief introduction of Backbone.js where you can learn the very basics of backbone.

Transcript of Backbonejs

Page 1: Backbonejs

Backbone.js

Ankit ShuklaEmail: [email protected]

Page 2: Backbonejs

What is Backbone.js?

➢ Backbone.js is a lightweight JavaScript library that adds structure to your client-side code. It makes it easy to manage and decouple concerns in your application, leaving you with code that is more maintainable in the long term.

➢ Developers commonly use libraries like Backbone.js to create single-page applications (SPAs).

Page 3: Backbonejs

Why we use Backbone.js?

● It's smaller. There are fewer kilobytes for your browser or phone to download, and less conceptual surface area.

● Backbone does not force you to use a single template engine.

● Backbone scales well, from embedded widgets to massive apps.

● Backbone is a library, not a framework, and plays well with others.

Page 4: Backbonejs

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:

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

Initialization:

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

Page 5: Backbonejs

Cont...

Default values:

There are times when you want your model to have a set of default values (e.g., in a scenario where a complete set of data isn’t provided by the user). You can set these using a property called defaults in your model.

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.

Page 6: Backbonejs

Cont...var Todo = Backbone.Model.extend({initialize: function(){console.log('This model has been initialized.');}});defaults: {title: '',completed: false},var myTodo = new Todo();// Logs: This model has been initialized.var todo3 = new Todo({title: 'New Title.',completed: true});console.log('Todo title: ' + myTodo.get('title'));// Todo title: Set through instantiation.console.log('Completed: ' + myTodo.get('completed'));// Completed: false// Set single attribute value at a time through Model.set():myTodo.set("title", "Title attribute set through Model.set().");console.log('Todo title: ' + myTodo.get('title'));

Page 7: Backbonejs

View

➢ Contain the logic behind the presentation of the model’s data to the user. They achieve this using JavaScript templating (for example, Underscore microtemplates, Mustache, jQuery- tmpl, and so on).

➢ Creating a new view is relatively straightforward and similar to creating new models.To create a new view, simply use Backbone.View .extend

Page 8: Backbonejs

Cont...

What Is el?

el is basically a reference to a DOM element. There are two ways to associate a DOM element with a view: a new element can be created for the view and subsequently added to the DOM, or a reference can be made to an element that already exists in the page.

If you want to create a new element for your view, set any combination of the followingproperties on the view: tagName , id , and className . The framework will create a newelement for you, and a reference to it will be available at the el property. If nothing isspecified, tagName defaults to div .

Page 9: Backbonejs

Cont...

var TodosView = Backbone.View.extend({

tagName: 'ul',

className: 'container',

id: 'todos',

});

var todosView = new TodosView();

console.log(todosView.el);

The preceding code creates the following DOM element but doesn’t append it to the

DOM.

<ul id="todos" class="container"></ul>

If the element already exists in the page, you can set el as a CSS selector that matches the element.

el: '#footer'

Page 10: Backbonejs

Collections

Collections

Collections are sets of models, and you create them by extending Backbone.Collection .

Adding and Removing Models

var Todo = Backbone.Model.extend({

defaults: {

title: '',

completed: false

}

});

Page 11: Backbonejs

Cont...

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 12: Backbonejs

Cont...

Retrieving Models

There are a few different ways to retrieve a model from a collection. The most straight‐forward is to use Collection.get() , which accepts a single id as follows:

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

// pass array of models on collection instantiation

var todos = new TodosCollection([myTodo]);

var todo2 = todos.get(2);

Page 13: Backbonejs

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 14: Backbonejs

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 15: Backbonejs

Dependencies

Backbone’s only hard dependency is either Underscore.js ( >= 1.4.3) or Lo-Dash. For RESTful persistence, history support via Backbone.Router and DOM manipulation with Backbone.View, include json2.js, and either jQuery ( >= 1.7.0) or Zepto.

Page 16: Backbonejs

Thank You