Upload
divakar-gu
View
74
Download
3
Embed Size (px)
DESCRIPTION
Backbonejs ppt for beginners
Citation preview
Backbone.js
-Divakar Gujjala
Topics
Overview
Models & Collections
Views & Templates
Routers
Events
History1995: JavaScript 2000: XMLHttpRequest
2006: jQuery 2010: Backbonejs
Overview
What?
Why?
Who?
Dependencies
What
Client side MVC fashion framework
Backbone.js was created by Jeremy Ashkenas,
author of the CoffeScript in 2010 (Oct 13th).
MIT licensed and on GitHub
RESTful JSON connector
Hash-Routing Engine
DOM AccessorAnimation toolkitControl suitAll in wonder package
Is notIs
Why
StructureReuseSeparation of Roles of concernsFlexibleLightweight (6.9kb)ModularPerfect OOP designCommunity
MV* Frameworks
Who uses Backbone.js?
What should I know?
Jquery
HTML
Template Engine (_, Mustage.js, Handlebars.js)
Json2.js (IE, other without json)
MVC Backbone.js
Architecture
REST APIROUTER
VIEW
MODELBROWSERAPP SERVER & DATABASE
Modules
Views
Events
Models
Collections
Routers
Events
A mixin which allows to dispatch events and register callbacks
Backbone's key feature, included by Model, Collection, View and History
Methods: on, off, trigger
REST
REST in Backbone.js
var PostModel = Backbone.Model.extend({ // Override id attribute. idAttribute: '_id', // Define URL root to access model resource. Otherwise use // url() method to provide full path to the model resource. urlRoot: function() { return 'http://example.com/posts/'; }});
var PostCollection = Backbone.Collection.extend({ model: PostModel, // Define path to the collection resource. url: function() { return 'http://example.com/posts/'; }});
REST in Backbone.js// Fetches data into a model.model.fetch();
// Saves a model.model.save();
// Destroys a model.model.destroy();
// Fetches data into a collection.collection.fetch();
// Adds models to a collection.collection.add(models);
// Removes specific models from collection.collection.remove(models);
Model Data storage and business logic
Key feature: the attributes hash
Changes on the attributes will fire change events
Models may be retrieved from and saved to a data
storage
Standard sync uses RESTful HTTP
Validation constraints
Methods• extend• constructor / initialize• get• set• escape• has• unset• clear• id• idAttribute• cid• attributes• changed• defaults• toJSON• sync• fetch• save• destroy• Underscore Methods (6)• validate• validationError• isValid• url• urlRoot• parse• clone• isNew• hasChanged• changedAttributes• previous• previousAttributes
Model
var Sidebar = Backbone.Model.extend({ promptColor: function() { var cssColor = prompt("Please enter a CSS color:"); this.set({color: cssColor}); }});
window.sidebar = new Sidebar;
sidebar.on('change:color', function(model, color) { $('#sidebar').css({background: color});});
sidebar.set({color: 'white'});
sidebar.promptColor();
Model
var Employee = Backbone.Model.extend({ defaults: { name: 'Divakar', location: ‘Location2', favoriteColor: 'blue', }}); var divakar = new Employee({ id: 1, name: 'Divakar', location:'Location2', favoriteColor: 'blue' });
var sudhakar = new Employee({ id: 2, name: 'Sudhakar', location: 'SEZ - Uppal', favoriteColor: 'green' });
var prabhakar = new Employee({ id: 3, name: 'Prabhakar', location: 'SEZ - Chennai', favoriteColor: 'red' });
Collections
A list of models
Fires add, remove and reset events
Implements underscore list helpers
Methods• extend• model• constructor / initialize• models• toJSON• sync• Underscore Methods (28)• add• remove• reset• set• get• at• push• pop• unshift• shift• slice• length• comparator• sort• pluck• where• findWhere• url• parse• clone• fetch• create
Viewvar 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() { ... }});
Collections
var Library = Backbone.Collection.extend({ model: Book});
var Library = Backbone.Collection.extend({ model: function(attrs, options) { if (condition) { return new PublicDocument(attrs, options); } else { return new PrivateDocument(attrs, options); } }});
View
A view owns a DOM element
Knows about its model or collection
Handles DOM events (user input)
Observes model events (binding)
Invokes model methods
Methods• extend• constructor / initialize• el• $el• setElement• attributes• $ (jQuery)• template• render• remove• delegateEvents• undelegateEvents
Router
A Router maps URIs to its methods
History is the actual workhorse, observe URI changes and fires callbacks
Hash URIs (location.hash, hashchange) or HTML5 History (pushState or popState )
Route usually creates models and views
Methods• extend• routes• constructor / initialize• route• navigate• execute
Router
var Workspace = Backbone.Router.extend({
routes: { "help": "help", // #help "search/:query": "search", // #search/kiwis "search/:query/p:page": "search" // #search/kiwis/p7 },
help: function() { ... },
search: function(query, page) { ... }});
Templates (Underscore.js) Javascript Utility Library
Fills in holes in the language
Provides functional support
Makes you happier writing javascript
MethodsCollections - each, map, filter, pluck, groupBy
Arrays - without, uniq
Functions - bind, debounce
Object - keys, values, is-*(Empty, Date, Function etc...), has
Utility - template, escape, mixin
Chaining - chain, value
Underscore.js
<script type="text/template" id=“employee-list-template"><table> <thead> <tr> <th>Name</th> <th>Location</th> <th>Favorite Color</th> </tr> </thead> <tbody> <% _.each(employees, function(employee) { %> <tr> <td><%= employee.get('name') %></td> <td><%= employee.get(‘location') %></td> <td><%= employee.get('favoriteColor') %></td> </tr> <% }); %> </tbody></table></script>
References
Backbone.JS http://backbonejs.org
Underscore.JS http://underscorejs.org
Developing Backbone.js Applications http://addyosmani.github.io/backbone-fundamentals/