Backbone.js
Upcoming SlideShare
Loading in...5
×
 

Backbone.js

on

  • 1,365 views

https://docs.google.com/presentation/d/1x82MkNUSewKaIOLNmCOpMrOxyeEcom8tSs5QXJIx5gs/edit#slide=id.gded62b8_0_22

https://docs.google.com/presentation/d/1x82MkNUSewKaIOLNmCOpMrOxyeEcom8tSs5QXJIx5gs/edit#slide=id.gded62b8_0_22

Statistics

Views

Total Views
1,365
Slideshare-icon Views on SlideShare
1,353
Embed Views
12

Actions

Likes
2
Downloads
37
Comments
0

3 Embeds 12

http://www.linkedin.com 7
http://localhost 3
https://www.linkedin.com 2

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Backbone.js Backbone.js Presentation Transcript

    • by:- Omnia Gamal El-Deen omnia.gamal1988@gmail.com twitter @Omnia_G
    • Agenda● Introduction into MVC, MVP, backbone● What is backbone?● Why backbone?● Backbone basics ○ Model ○ View ○ Collection ○ Router
    • Introduction● MVC "Model – View – Controller" ○ Mode ■ Collection ○ View ■ Templating ○ Controller ■ Controllers and Backbone.js● MVP "Model - view - presenter" ○ P ○ MVP or MVC● MVC, MVP and Backbone.js
    • MVC
    • Model● Manage the data for an application● When model changes -> itll typically notify its View that a change has occurred so that they may react accordingly.● var Shape = Backbone.Model.extend({ defaults: { x:50, y:50, width:150, height:150, color:black }});
    • Collection● Group of models together● managing models in groups allows us to write application logic based on notification from the group, should any model it contains change● var Document = Backbone.Collection.extend({ model: Shape });
    • Views● are a visual representation of models that present a filtered view of their current state.● var ShapeView = Backbone.View.extend();● Templating ○ Handlebars.js ○ Matache
    • Controllers● are an intermediary between models and views which are classically responsible for two tasks: ○ update the view when the model changes ○ and update the model when the user manipulates the view● C is change from MVC framework to other*● Does Backbone.js have Controllers? *● Router* ○ main purpose is to translate URL requests into application states.
    • MVP● P ○ All invocations from the View delegate directly to Presenter. ○ The Presenter is also decoupled directly from the View and talks to it through an interface. ○ This is to allow mocking of the View in a unit test.
    • MVC or MVP● MVP ○ is generally used most often in applications where it’ s necessary to reuse as much presentation logic as possible. ○ Applications with very complex views and a great deal of user interaction may find that MVC doesn’t quite fit the bill here as solving this problem may mean heavily relying on multiple controllers. ○ MVP may be more easy to automatically unit test than MVC*
    • MVC, MVP and Backbone.js● Is Backbone MVC or MVP?
    • What is backbone?● Created by Jeremy Ashkenas, creator of CoffeeScript, Docco and Underscore.js.● Client-side development framework● MV* framework● can be easily tested using third-party toolkits such as Jasmine or QUnit
    • Application
    • Why backbone?● Organize your code in (model - collection- views) ○ No more Free-hanging ○ No more Unrelated blocks of code● no more complex UI synch code● RESTful● Decouple the DOM from your pages data
    • Backbone basics● Backbone dependencies 1. jQuery, Zepto 2. underscore.js 3. _.template, Handlebars.js 4. For Test Jasmine.js or QUnit● Backbone component 1. Models 2. Collections 3. Views 4. Routers
    • HTML<!DOCTYPE html><html><head> <title>hello-backbone.js</title></head><body> <!-- Backbone dependencies --> <script src="libs/jquery.min.js"></script> <script src="libs/underscore-min.js"></script> <script src="libs/backbone-min.js"></script> <!-- src Code --> <script src="....js file...."></script></body></html>
    • 1. Model● Store data● attributes hash● fire events when data is changed● (function($){ var Item = Backbone.Model.extend({ defaults: { part1: hello, part2: world } }); })(jQuery);
    • cont. Model● defaults: There are times when you want your model to have a set of default values. This can be set using a property called defaults in your model. ○ var item = new Item(); ○ var item = new Item({"part1": "welcome", "part2": "to c9" });● constructor / initialize : When creating an instance of a model, you can pass in the initial values of theattributes, which will be set on the model. If you define an initialize function, it will be invoked when the model is created.
    • cont. Model● Getters & Setters ○ Model.get() ■ var item = new Item(); console.log("//Get Model attributesnpart1: ", item.get("part1")); ○ Model.set() ■ item.set("part1", "welcome"); console.log("//After set model by new valuesnpart1: ", item.get ("part1")) ○ Model.attributes ■ console.log("Model Attributes", item.attributes); ○ Model.toJSON() ■ console.log("Model Attributes as JSON", item.toJSON());
    • cont. Model● Listening for changes to your model ○ initialize: function(){ console.log(this model has been initialized); this.on("change:part1", function(model){ var part1 = this.get("part1"); console.log("My part1 has been changed to.. " + part1); }); }, setPart1: function(newPart){ this.set("part1", newPart); }
    • cont. Model● Validation ○ Backbone supports model validation through Model. validate(), which allows checking the attribute values for a model prior to them being set. ○ 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, a custom error can be returned instead. ○ validate: function(attribs){ if(attribs.part3 === undefined){ return "Remember to set a part3!"; }} ○ item.set({ "part3": "hi" });
    • 2. Collection● sets of Modelsvar List = Backbone.Collection.extend({ model: Item });● Getters and Setters ○ Collection.models : ■ itemlist = new List([item, item2]); ■ console.log(itemlist.models); ○ get : collection.get(id) Get a model from a collection, specified by id. ■ console.log(itemlist.at(1).get("part1"));
    • cont. Collectio ○ remove: Remove a model (or an array of models) from the collection ■ itemlist.remove(item); console.log("After remove item",itemlist.models) ;● Underscore utility functions (28) ○ Collections ■ sortBy: Returns a sorted copy of list ● sort :function(){ return this.sortBy(function (item) { return item.get("part1"). toLowerCase(); }); } ○ Arrays ○ Function ○ Object ○ Utility ○ Chaining
    • 3. View● Display Data● Description of a model● Render data with template● Respond to model data changes● Act on user input entries● var ListView = Backbone.View.extend({ el: $(body), events: { click button#add: addItem }});
    • cont. View● What is el? ○ el is basically a reference to a DOM element and all views must have one. ○ It allows for all of the contents of a view to be inserted into the DOM at once ○ There are two ways to attach a DOM element to a view: i. the element already exists in the page ii. a new element is created for the view and added manually by the developer. ○ If the element already exists in the page:- ● el: #elem_id, ● // OR ● el: document.getElementById( body )
    • cont. View ○ If you want to create a new element for your view, set any combination of the following view’s properties: tagName, id and className.A new element will be created for you by theframework and a reference to it will be availableat the el property. ● tagName: p, // required, but defaults to div if not set className: container, // optional, you can assign multiple classes to this property like so container id: header, // optional ● The above code creates the DOMElement below but doesn’t append it to the DOM. <p id="header" class="container"></p>
    • initialize: function(){ _.bindAll(this, render, addItem, appendItem); // remember: every function that uses this as the current objectshould be in here this.collection = new List(); this.collection.bind(add, this.appendItem); // collection event binder this.counter = 0; this.render(); },render: function(){ var self = this; $(this.el).append("<button id=add>Add list item</button>"); $(this.el).append("<ul></ul>"); _(this.collection.models).each(function(item){ // in case collection is not empty self.appendItem(item); }, this); },
    • cont. View● initialize(): method is called when a new instance of a model is created. Its use is optional● render(): is an optional function that defines the logic for rendering a template ○ $(this.el).append("<button id=add>Add list item</button>"); ○ $(this.el).append("<ul></ul>");
    • addItem: function(){ this.counter++; var item = new Item(); item.set({ part2: item.get(part2) + this.counter // modify item defaults }); this.collection.add(item); // add item to collection; view isupdated via event add },appendItem: function(item){ $(ul, this.el).append("<li>"+item.get(part1)+" "+item.get(part2)+"</li>"); } }); var listView = new ListView();
    • 4. Routers● used to help manage application state and for connecting URLs to application events.● This is achieved using hash-tags with URL fragments, or using the browser’s pushState and History API● var GalleryRouter = Backbone.Router.extend({ routes: { "about" : "showAbout", "items/:id" : "getItem",}, showAbout: function(){ }, getItem: function(id){ console.log("You are trying to reach item " + id); },
    • Backbone.history● Backbone.history is where Backbone stores all of the places you’ve been.● This is necessary in order to not break the back button in your browser.● The Backbone.history.start() method will simply tell Backbone that it’s OK to begin monitoring all hashchange events as follows: ○ Backbone.history.start();