SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
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 -> it'll 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 page's 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
Backbone.js
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 Models
var 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 the
framework and a reference to it will be available
at 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 object
should 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 is
updated 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();
Backbone.js

Weitere ähnliche Inhalte

Was ist angesagt?

Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest servicesIoan Eugen Stan
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript TestingScott Becker
 
One step in the future: CSS variables
One step in the future: CSS variablesOne step in the future: CSS variables
One step in the future: CSS variablesGiacomo Zinetti
 
Webpack Tutorial, Uppsala JS
Webpack Tutorial, Uppsala JSWebpack Tutorial, Uppsala JS
Webpack Tutorial, Uppsala JSEmil Öberg
 
PHP MVC Tutorial
PHP MVC TutorialPHP MVC Tutorial
PHP MVC TutorialYang Bruce
 
The Complementarity of React and Web Components
The Complementarity of React and Web ComponentsThe Complementarity of React and Web Components
The Complementarity of React and Web ComponentsAndrew Rota
 
Javascript MVVM with Vue.JS
Javascript MVVM with Vue.JSJavascript MVVM with Vue.JS
Javascript MVVM with Vue.JSEueung Mulyana
 
webpack 101 slides
webpack 101 slideswebpack 101 slides
webpack 101 slidesmattysmith
 
Packing for the Web with Webpack
Packing for the Web with WebpackPacking for the Web with Webpack
Packing for the Web with WebpackThiago Temple
 
Workshop 9: BackboneJS y patrones MVC
Workshop 9: BackboneJS y patrones MVCWorkshop 9: BackboneJS y patrones MVC
Workshop 9: BackboneJS y patrones MVCVisual Engineering
 
AngularJS Deep Dives (NYC GDG Apr 2013)
AngularJS Deep Dives (NYC GDG Apr 2013)AngularJS Deep Dives (NYC GDG Apr 2013)
AngularJS Deep Dives (NYC GDG Apr 2013)Nitya Narasimhan
 
React Facebook JavaScript Library
React Facebook JavaScript LibraryReact Facebook JavaScript Library
React Facebook JavaScript LibraryTakami Kazuya
 
Introduction to VueJS & Vuex
Introduction to VueJS & VuexIntroduction to VueJS & Vuex
Introduction to VueJS & VuexBernd Alter
 
Service Worker 201 (en)
Service Worker 201 (en)Service Worker 201 (en)
Service Worker 201 (en)Chang W. Doh
 

Was ist angesagt? (20)

Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest services
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript Testing
 
One step in the future: CSS variables
One step in the future: CSS variablesOne step in the future: CSS variables
One step in the future: CSS variables
 
Web components
Web componentsWeb components
Web components
 
Webpack Tutorial, Uppsala JS
Webpack Tutorial, Uppsala JSWebpack Tutorial, Uppsala JS
Webpack Tutorial, Uppsala JS
 
PHP MVC Tutorial
PHP MVC TutorialPHP MVC Tutorial
PHP MVC Tutorial
 
The Complementarity of React and Web Components
The Complementarity of React and Web ComponentsThe Complementarity of React and Web Components
The Complementarity of React and Web Components
 
Javascript MVVM with Vue.JS
Javascript MVVM with Vue.JSJavascript MVVM with Vue.JS
Javascript MVVM with Vue.JS
 
webpack 101 slides
webpack 101 slideswebpack 101 slides
webpack 101 slides
 
Packing for the Web with Webpack
Packing for the Web with WebpackPacking for the Web with Webpack
Packing for the Web with Webpack
 
Workshop 9: BackboneJS y patrones MVC
Workshop 9: BackboneJS y patrones MVCWorkshop 9: BackboneJS y patrones MVC
Workshop 9: BackboneJS y patrones MVC
 
Thomas Fuchs Presentation
Thomas Fuchs PresentationThomas Fuchs Presentation
Thomas Fuchs Presentation
 
Dan Webb Presentation
Dan Webb PresentationDan Webb Presentation
Dan Webb Presentation
 
Night Watch with QA
Night Watch with QANight Watch with QA
Night Watch with QA
 
Knockout.js
Knockout.jsKnockout.js
Knockout.js
 
AngularJS Deep Dives (NYC GDG Apr 2013)
AngularJS Deep Dives (NYC GDG Apr 2013)AngularJS Deep Dives (NYC GDG Apr 2013)
AngularJS Deep Dives (NYC GDG Apr 2013)
 
React Facebook JavaScript Library
React Facebook JavaScript LibraryReact Facebook JavaScript Library
React Facebook JavaScript Library
 
Introduction to VueJS & Vuex
Introduction to VueJS & VuexIntroduction to VueJS & Vuex
Introduction to VueJS & Vuex
 
Service Worker 201 (en)
Service Worker 201 (en)Service Worker 201 (en)
Service Worker 201 (en)
 
Webpack
WebpackWebpack
Webpack
 

Ähnlich wie Backbone.js

Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsRavi Bhadauria
 
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...Christian Janz
 
Using a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsUsing a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsallanh0526
 
Thinking in Components
Thinking in ComponentsThinking in Components
Thinking in ComponentsAnton Ivanov
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJsTudor Barbu
 
Creating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSCreating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSAkshay Mathur
 
Swift Tableview iOS App Development
Swift Tableview iOS App DevelopmentSwift Tableview iOS App Development
Swift Tableview iOS App DevelopmentKetan Raval
 
MobileCity:Core Data
MobileCity:Core DataMobileCity:Core Data
MobileCity:Core DataAllan Davis
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs WorkshopRan Wahle
 
Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Ovadiah Myrgorod
 

Ähnlich wie Backbone.js (20)

Backbonejs
BackbonejsBackbonejs
Backbonejs
 
Backbone Basics with Examples
Backbone Basics with ExamplesBackbone Basics with Examples
Backbone Basics with Examples
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
AngularJS Workshop
AngularJS WorkshopAngularJS Workshop
AngularJS Workshop
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
 
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...
 
Using a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsUsing a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS apps
 
Thinking in Components
Thinking in ComponentsThinking in Components
Thinking in Components
 
Django
DjangoDjango
Django
 
Angular js
Angular jsAngular js
Angular js
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
 
Creating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSCreating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JS
 
Swift Tableview iOS App Development
Swift Tableview iOS App DevelopmentSwift Tableview iOS App Development
Swift Tableview iOS App Development
 
MobileCity:Core Data
MobileCity:Core DataMobileCity:Core Data
MobileCity:Core Data
 
Backbone js
Backbone jsBackbone js
Backbone js
 
AngularJS.part1
AngularJS.part1AngularJS.part1
AngularJS.part1
 
mean stack
mean stackmean stack
mean stack
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
 
Frontend training
Frontend trainingFrontend training
Frontend training
 
Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8
 

Kürzlich hochgeladen

UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-pyJamie (Taka) Wang
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 

Kürzlich hochgeladen (20)

UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-py
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 

Backbone.js

  • 1. by:- Omnia Gamal El-Deen omnia.gamal1988@gmail.com 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 -> it'll 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
  • 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 page's 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
  • 17. 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>
  • 18. 1. Model ● Store data ● attributes hash ● fire events when data is changed ● (function($){ var Item = Backbone.Model.extend({ defaults: { part1: 'hello', part2: 'world' } }); })(jQuery);
  • 19. 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.
  • 20. 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());
  • 21. 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); }
  • 22. 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" });
  • 23. 2. Collection ● sets of Models var 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"));
  • 24. 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
  • 25. 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' }});
  • 26. 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' )
  • 27. 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 the framework and a reference to it will be available at 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>
  • 28. initialize: function(){ _.bindAll(this, 'render', 'addItem', 'appendItem'); // remember: every function that uses 'this' as the current object should 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); },
  • 29. 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>");
  • 30. 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 is updated via event 'add' }, appendItem: function(item){ $('ul', this.el).append("<li>"+item.get('part1')+" "+item.get ('part2')+"</li>"); } }); var listView = new ListView();
  • 31. 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); },
  • 32. 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();