SlideShare a Scribd company logo
1 of 28
Download to read offline
Developing
                 JavaScript
             Widgets



Konstantin
Käfer
1   Functions

    2   Drupal’s JavaScript facilities

    3   Widgets

    4   Debugging & Analyzing


2                                        Konstantin Käfer
Functions
        Functions are first class entities
    ‣

        – Store in variables, pass as parameters, return from
          functions
        – Can be defined at any place

        Functions can contain properties
    ‣

        Anonymous functions
    ‣




3                                                           Konstantin Käfer
Functions (II)
    var foo = function(callback) {
      callback();
      return function() {
        print(quot;Returned function calledquot;);
      };
    };

    foo(function() {
      print(quot;Passed function calledquot;);
    })();

    foo.bar = quot;bazquot;;


4                                            Konstantin Käfer
Prototypal OOP
        JavaScript doesn’t have classes
    ‣

        Prototype of a function used as base class
    ‣

        var Foo = function() { /* ... */ };

        Foo.prototype = {
          'bar': function() { /* ... */ },
          'baz': function() { /* ... */ }
        };

        var instance = new Foo();
        instance.bar();
        instance.baz();
5                                                    Konstantin Käfer
Prototypal OOP (II)
        Function is constructor
    ‣

        “Instances” have an implicit link to the base
    ‣
        class
        var Foo = function() { /* ... */ };
        Foo.prototype = {
          'bar': function() { /* ... */ }
        };

        var instance = new Foo();
        instance.bar();

        Foo.prototype.baz = function() { /* ... */ };
        instance.baz();
6                                                       Konstantin Käfer
Prototypal OOP (III)
        Any objects can be extended/changed at any
    ‣
        time
    Number.prototype.celsiusToFahrenheit = function() {
      return (this * 9 / 5) + 32;
    };

    js> (34).celsiusToFahrenheit();
    93.2
    js> (0).celsiusToFahrenheit();
    32



7                                                    Konstantin Käfer
1   Functions

    2   Drupal’s JavaScript facilities

    3   Widgets

    4   Debugging & Analyzing


8                                        Konstantin Käfer
AJAX Callbacks
        In the menu system:
    ‣
        $items['mymodule/js'] = array(
          'title' => 'JavaScript callback',
          'page callback' => 'mymodule_js',
          'access callback' => TRUE,
          'type' => MENU_CALLBACK,
        );

        Menu callback:
    ‣
        function mymodule_js() {
          // Generate $data...
          drupal_json($data);
        }
9                                             Konstantin Käfer
Translation
         Similar to PHP
     ‣

         Drupal.t('This is a string.');
     ‣


         Drupal.t('Do you really want to delete %object?',
     ‣
           { '%object': object.name });

         Drupal.formatPlural(count,
     ‣
           '1 comment', '@count comments');

         POT extractor and Drupal parse JavaScript files
     ‣




10                                                    Konstantin Käfer
Behaviors
         All functions in Drupal.behaviors are executed
     ‣
         onready (when the DOM is ready)

         Functions have to be non-destructive
     ‣

         Functions get a context parameter to act on
     ‣

         Advantage: Can be called later as well
     ‣

         Drupal.behaviors.foo = function(context) {
     ‣

           $('.foo:not(.foo-processed)', context).each(
             function() { … }
           );
         };
11                                                     Konstantin Käfer
Theming
         Theme functions for HTML code
     ‣

         Advantage: Themes can change markup
     ‣

         In the module’s JavaScript:
     ‣
         var elem = Drupal.theme('mymodule');
         $('body').append(elem);

         Drupal.theme.prototype.mymodule = function() { /*...*/ }

         In the theme’s JavaScript:
     ‣
         Drupal.theme.mymodule = function() {
           return $('<div class=quot;mymodulequot;></div>');
         }

12                                                          Konstantin Käfer
1   Functions

     2   Drupal’s JavaScript facilities

     3   Widgets

     4   Debugging & Analyzing


13                                        Konstantin Käfer
Compatibility



14                   Konstantin Käfer
Reusability



15                 Konstantin Käfer
Flexibility



16                 Konstantin Käfer
Encapsulation



17                   Konstantin Käfer
Speed



18           Konstantin Käfer
Initializing
     Drupal.behaviors.horizscroll =
                                 function(context) {
       $('.horizscroll:not(.horizscroll-processed)',
           context).each(function() {

        // <<< Initialize the horizscroll >>>

       }).addClass('horizscroll-processed');
     };




19                                              Konstantin Käfer
Constructor
     Drupal.horizscroll = function(options) {
       var that = this;

      $.extend(this, options);

       //   Store references to elements.
       //   Set first element as the quot;target item.quot;
       //   Initialize left and right buttons.
       //   Initialize the button status.
     };


20                                               Konstantin Käfer
Methods
     Drupal.horizScroll.prototype = {
       // Update the button status based on the
       // position of the content.
       'updateButtons': function() { },

      // Moves the content box to an item.
      'scrollToItem': function() { },

       // Calculate the next target item.
       'findTarget': function() { }
     };

21                                                Konstantin Käfer
1   Functions

     2   Drupal’s JavaScript facilities

     3   Widgets

     4   Debugging & Analyzing


22                                        Konstantin Käfer
Advanced JavaScript console
     ‣

         Logging to the console (console.log())
     ‣

         DOM inspector
     ‣

         JavaScript debugger (with backtrace!)
     ‣

         Profile JavaScript activity
     ‣



         http://getfirebug.com
     ‣

23                                                Konstantin Käfer
JavaScript debugger for IE
     ‣

         Free of charge
     ‣

         Some configuration work needed
     ‣



         http://msdn.microsoft.com/vstudio/express/
     ‣
         vwd/



24                                                Konstantin Käfer
WebDevHelper
         JavaScript console for IE
     ‣

         HTTP Logger
     ‣

         JavaScript backtracer
     ‣



         http://projects.nikhilk.net/WebDevHelper/
     ‣
         Default.aspx




25                                                   Konstantin Käfer
JavaScript Lint
         Lint = tool for analyzing code
     ‣

         Discovers sloppy coding
     ‣

         Command line interface
     ‣

         Use as pre-commit hook for <insert RCS>
     ‣



         http://javascriptlint.com
     ‣

         TextMate bundle: http://andrewdupont.net/
     ‣
         2006/10/01/javascript-tools-textmate-bundle/
26                                                 Konstantin Käfer
Thanks! Questions?



        Konstantin Käfer
          mail@kkaefer.com




27                           Konstantin Käfer
Further reading
         Example taken from
     ‣
         “Front End Drupal”


         Pre-order on Amazon!
     ‣

         Now on Safari Online
     ‣

         In stores in April
     ‣




28                              Konstantin Käfer

More Related Content

What's hot

Virtualize and automate your development environment for fun and profit
Virtualize and automate your development environment for fun and profitVirtualize and automate your development environment for fun and profit
Virtualize and automate your development environment for fun and profitAndreas Heim
 
Advanced JavaScript Concepts
Advanced JavaScript ConceptsAdvanced JavaScript Concepts
Advanced JavaScript ConceptsNaresh Kumar
 
Introdução ao Desenvolvimento Android com Kotlin
Introdução ao Desenvolvimento Android com KotlinIntrodução ao Desenvolvimento Android com Kotlin
Introdução ao Desenvolvimento Android com KotlinNelson Glauber Leal
 
Kotlin For Android - Basics (part 1 of 7)
Kotlin For Android - Basics (part 1 of 7)Kotlin For Android - Basics (part 1 of 7)
Kotlin For Android - Basics (part 1 of 7)Gesh Markov
 
ClojureScript: The Good Parts
ClojureScript: The Good PartsClojureScript: The Good Parts
ClojureScript: The Good PartsKent Ohashi
 
Kotlin For Android - Constructors and Control Flow (part 2 of 7)
Kotlin For Android - Constructors and Control Flow (part 2 of 7)Kotlin For Android - Constructors and Control Flow (part 2 of 7)
Kotlin For Android - Constructors and Control Flow (part 2 of 7)Gesh Markov
 
Aplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e JetpackAplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e JetpackNelson Glauber Leal
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftFlorent Pillet
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaFlorent Pillet
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & CollectionsCocoaHeads France
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsLeonardo Borges
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streamsmattpodwysocki
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node jsThomas Roch
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
RDSDataSource: Мастер-класс по Dip
RDSDataSource: Мастер-класс по DipRDSDataSource: Мастер-класс по Dip
RDSDataSource: Мастер-класс по DipRAMBLER&Co
 
Realm.io par Clement Sauvage
Realm.io par Clement SauvageRealm.io par Clement Sauvage
Realm.io par Clement SauvageCocoaHeads France
 

What's hot (20)

Virtualize and automate your development environment for fun and profit
Virtualize and automate your development environment for fun and profitVirtualize and automate your development environment for fun and profit
Virtualize and automate your development environment for fun and profit
 
Advanced JavaScript Concepts
Advanced JavaScript ConceptsAdvanced JavaScript Concepts
Advanced JavaScript Concepts
 
Introdução ao Desenvolvimento Android com Kotlin
Introdução ao Desenvolvimento Android com KotlinIntrodução ao Desenvolvimento Android com Kotlin
Introdução ao Desenvolvimento Android com Kotlin
 
Kotlin For Android - Basics (part 1 of 7)
Kotlin For Android - Basics (part 1 of 7)Kotlin For Android - Basics (part 1 of 7)
Kotlin For Android - Basics (part 1 of 7)
 
Map kit light
Map kit lightMap kit light
Map kit light
 
Kotlin wonderland
Kotlin wonderlandKotlin wonderland
Kotlin wonderland
 
ClojureScript: The Good Parts
ClojureScript: The Good PartsClojureScript: The Good Parts
ClojureScript: The Good Parts
 
Kotlin For Android - Constructors and Control Flow (part 2 of 7)
Kotlin For Android - Constructors and Control Flow (part 2 of 7)Kotlin For Android - Constructors and Control Flow (part 2 of 7)
Kotlin For Android - Constructors and Control Flow (part 2 of 7)
 
Aplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e JetpackAplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e Jetpack
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & Collections
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
Présentation de HomeKit
Présentation de HomeKitPrésentation de HomeKit
Présentation de HomeKit
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
RDSDataSource: Мастер-класс по Dip
RDSDataSource: Мастер-класс по DipRDSDataSource: Мастер-класс по Dip
RDSDataSource: Мастер-класс по Dip
 
Realm.io par Clement Sauvage
Realm.io par Clement SauvageRealm.io par Clement Sauvage
Realm.io par Clement Sauvage
 

Similar to Developing JavaScript Widgets

Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...
Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...
Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...Techsylvania
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?Christophe Porteneuve
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...
No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...
No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...Atlassian
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
W3C HTML5 KIG-How to write low garbage real-time javascript
W3C HTML5 KIG-How to write low garbage real-time javascriptW3C HTML5 KIG-How to write low garbage real-time javascript
W3C HTML5 KIG-How to write low garbage real-time javascriptChanghwan Yi
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
[Kotlin Serverless 工作坊] 單元 4 - 實作 RSS Aggregator
[Kotlin Serverless 工作坊] 單元 4 - 實作 RSS Aggregator[Kotlin Serverless 工作坊] 單元 4 - 實作 RSS Aggregator
[Kotlin Serverless 工作坊] 單元 4 - 實作 RSS AggregatorShengyou Fan
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxbobmcwhirter
 
Building High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterBuilding High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterMithun T. Dhar
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
 

Similar to Developing JavaScript Widgets (20)

Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...
Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...
Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...
 
Java script
Java scriptJava script
Java script
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Swift core
Swift coreSwift core
Swift core
 
JS Essence
JS EssenceJS Essence
JS Essence
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...
No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...
No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
W3C HTML5 KIG-How to write low garbage real-time javascript
W3C HTML5 KIG-How to write low garbage real-time javascriptW3C HTML5 KIG-How to write low garbage real-time javascript
W3C HTML5 KIG-How to write low garbage real-time javascript
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
[Kotlin Serverless 工作坊] 單元 4 - 實作 RSS Aggregator
[Kotlin Serverless 工作坊] 單元 4 - 實作 RSS Aggregator[Kotlin Serverless 工作坊] 單元 4 - 實作 RSS Aggregator
[Kotlin Serverless 工作坊] 單元 4 - 實作 RSS Aggregator
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBox
 
Building High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterBuilding High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 Firestarter
 
From * to Symfony2
From * to Symfony2From * to Symfony2
From * to Symfony2
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 

More from Konstantin Käfer

More from Konstantin Käfer (6)

Instant Dynamic Forms with #states
Instant Dynamic Forms with #statesInstant Dynamic Forms with #states
Instant Dynamic Forms with #states
 
Front End Performance
Front End PerformanceFront End Performance
Front End Performance
 
Front End Performance
Front End PerformanceFront End Performance
Front End Performance
 
Front End Performance
Front End PerformanceFront End Performance
Front End Performance
 
Typography on the Web
Typography on the WebTypography on the Web
Typography on the Web
 
What's New in Web Development
What's New in Web DevelopmentWhat's New in Web Development
What's New in Web Development
 

Recently uploaded

Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 

Recently uploaded (20)

Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 

Developing JavaScript Widgets

  • 1. Developing JavaScript Widgets Konstantin Käfer
  • 2. 1 Functions 2 Drupal’s JavaScript facilities 3 Widgets 4 Debugging & Analyzing 2 Konstantin Käfer
  • 3. Functions Functions are first class entities ‣ – Store in variables, pass as parameters, return from functions – Can be defined at any place Functions can contain properties ‣ Anonymous functions ‣ 3 Konstantin Käfer
  • 4. Functions (II) var foo = function(callback) { callback(); return function() { print(quot;Returned function calledquot;); }; }; foo(function() { print(quot;Passed function calledquot;); })(); foo.bar = quot;bazquot;; 4 Konstantin Käfer
  • 5. Prototypal OOP JavaScript doesn’t have classes ‣ Prototype of a function used as base class ‣ var Foo = function() { /* ... */ }; Foo.prototype = { 'bar': function() { /* ... */ }, 'baz': function() { /* ... */ } }; var instance = new Foo(); instance.bar(); instance.baz(); 5 Konstantin Käfer
  • 6. Prototypal OOP (II) Function is constructor ‣ “Instances” have an implicit link to the base ‣ class var Foo = function() { /* ... */ }; Foo.prototype = { 'bar': function() { /* ... */ } }; var instance = new Foo(); instance.bar(); Foo.prototype.baz = function() { /* ... */ }; instance.baz(); 6 Konstantin Käfer
  • 7. Prototypal OOP (III) Any objects can be extended/changed at any ‣ time Number.prototype.celsiusToFahrenheit = function() { return (this * 9 / 5) + 32; }; js> (34).celsiusToFahrenheit(); 93.2 js> (0).celsiusToFahrenheit(); 32 7 Konstantin Käfer
  • 8. 1 Functions 2 Drupal’s JavaScript facilities 3 Widgets 4 Debugging & Analyzing 8 Konstantin Käfer
  • 9. AJAX Callbacks In the menu system: ‣ $items['mymodule/js'] = array( 'title' => 'JavaScript callback', 'page callback' => 'mymodule_js', 'access callback' => TRUE, 'type' => MENU_CALLBACK, ); Menu callback: ‣ function mymodule_js() { // Generate $data... drupal_json($data); } 9 Konstantin Käfer
  • 10. Translation Similar to PHP ‣ Drupal.t('This is a string.'); ‣ Drupal.t('Do you really want to delete %object?', ‣ { '%object': object.name }); Drupal.formatPlural(count, ‣ '1 comment', '@count comments'); POT extractor and Drupal parse JavaScript files ‣ 10 Konstantin Käfer
  • 11. Behaviors All functions in Drupal.behaviors are executed ‣ onready (when the DOM is ready) Functions have to be non-destructive ‣ Functions get a context parameter to act on ‣ Advantage: Can be called later as well ‣ Drupal.behaviors.foo = function(context) { ‣ $('.foo:not(.foo-processed)', context).each( function() { … } ); }; 11 Konstantin Käfer
  • 12. Theming Theme functions for HTML code ‣ Advantage: Themes can change markup ‣ In the module’s JavaScript: ‣ var elem = Drupal.theme('mymodule'); $('body').append(elem); Drupal.theme.prototype.mymodule = function() { /*...*/ } In the theme’s JavaScript: ‣ Drupal.theme.mymodule = function() { return $('<div class=quot;mymodulequot;></div>'); } 12 Konstantin Käfer
  • 13. 1 Functions 2 Drupal’s JavaScript facilities 3 Widgets 4 Debugging & Analyzing 13 Konstantin Käfer
  • 14. Compatibility 14 Konstantin Käfer
  • 15. Reusability 15 Konstantin Käfer
  • 16. Flexibility 16 Konstantin Käfer
  • 17. Encapsulation 17 Konstantin Käfer
  • 18. Speed 18 Konstantin Käfer
  • 19. Initializing Drupal.behaviors.horizscroll = function(context) { $('.horizscroll:not(.horizscroll-processed)', context).each(function() { // <<< Initialize the horizscroll >>> }).addClass('horizscroll-processed'); }; 19 Konstantin Käfer
  • 20. Constructor Drupal.horizscroll = function(options) { var that = this; $.extend(this, options); // Store references to elements. // Set first element as the quot;target item.quot; // Initialize left and right buttons. // Initialize the button status. }; 20 Konstantin Käfer
  • 21. Methods Drupal.horizScroll.prototype = { // Update the button status based on the // position of the content. 'updateButtons': function() { }, // Moves the content box to an item. 'scrollToItem': function() { }, // Calculate the next target item. 'findTarget': function() { } }; 21 Konstantin Käfer
  • 22. 1 Functions 2 Drupal’s JavaScript facilities 3 Widgets 4 Debugging & Analyzing 22 Konstantin Käfer
  • 23. Advanced JavaScript console ‣ Logging to the console (console.log()) ‣ DOM inspector ‣ JavaScript debugger (with backtrace!) ‣ Profile JavaScript activity ‣ http://getfirebug.com ‣ 23 Konstantin Käfer
  • 24. JavaScript debugger for IE ‣ Free of charge ‣ Some configuration work needed ‣ http://msdn.microsoft.com/vstudio/express/ ‣ vwd/ 24 Konstantin Käfer
  • 25. WebDevHelper JavaScript console for IE ‣ HTTP Logger ‣ JavaScript backtracer ‣ http://projects.nikhilk.net/WebDevHelper/ ‣ Default.aspx 25 Konstantin Käfer
  • 26. JavaScript Lint Lint = tool for analyzing code ‣ Discovers sloppy coding ‣ Command line interface ‣ Use as pre-commit hook for <insert RCS> ‣ http://javascriptlint.com ‣ TextMate bundle: http://andrewdupont.net/ ‣ 2006/10/01/javascript-tools-textmate-bundle/ 26 Konstantin Käfer
  • 27. Thanks! Questions? Konstantin Käfer mail@kkaefer.com 27 Konstantin Käfer
  • 28. Further reading Example taken from ‣ “Front End Drupal” Pre-order on Amazon! ‣ Now on Safari Online ‣ In stores in April ‣ 28 Konstantin Käfer