Your SlideShare is downloading. ×
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply



Published on

  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 1. by:- Omnia Gamal El-Deen twitter @Omnia_G
  • 2. Agenda● Introduction into MVC, MVP, backbone● What is backbone?● Why backbone?● Backbone basics ○ Model ○ View ○ Collection ○ Router
  • 3. 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
  • 4. MVC
  • 5. 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 }});
  • 6. 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 });
  • 7. 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
  • 8. 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.
  • 9. 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.
  • 10. 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*
  • 11. MVC, MVP and Backbone.js● Is Backbone MVC or MVP?
  • 12. 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
  • 13. Application
  • 14. 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
  • 15. 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
  • 16. 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>
  • 17. 1. Model● Store data● attributes hash● fire events when data is changed● (function($){ var Item = Backbone.Model.extend({ defaults: { part1: hello, part2: world } }); })(jQuery);
  • 18. 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.
  • 19. 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());
  • 20. 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); }
  • 21. 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" });
  • 22. 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("part1"));
  • 23. 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
  • 24. 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 }});
  • 25. 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 )
  • 26. 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>
  • 27. 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); },
  • 28. 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>");
  • 29. 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();
  • 30. 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); },
  • 31. 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();