SlideShare uma empresa Scribd logo
1 de 35
JavaScript Coding
          with Class

© SitePen, Inc. All Rights Reserved
Who is David Walsh?

               Software Engineer for SitePen
               MooTools Team Member            - Add real photo of me

               David Walsh Blog scribe         - Slide in caricature



               Script & Style founder
               10 years working experience
               @davidwalshblog




© SitePen, Inc. All Rights Reserved
Class?

               Class patterns
                      As featured in most programming languages
                      Object-oriented methodology employed
               Beautiful code
                      .... a.k.a. programmer porn
                      Adheres to basic JavaScript coding practices




© SitePen, Inc. All Rights Reserved
Class...from a
                              Yank?

© SitePen, Inc. All Rights Reserved
(not class)




© SitePen, Inc. All Rights Reserved
(class)




© SitePen, Inc. All Rights Reserved
(not class)




                                      Add photo of:

                                      - Jordon
                                      - Boy George




© SitePen, Inc. All Rights Reserved
(class)




© SitePen, Inc. All Rights Reserved
Classes in JavaScript

               True “classes” are not provided by JavaScript
                      ....even though class is a reserved word
               Enclosure patterns, functions, and their prototypes are used
               to simulate classes
               Toolkits like Dojo and MooTools abstract those patterns to
               allow developers to create powerful, flexible classes




© SitePen, Inc. All Rights Reserved
Why Classes?

               Easier to read, understand, & maintain
                      Unified API despite type of task
               Inheritance Patterns
                      Easy to extend
                      “Don’t Repeat Yourself” philosophy employed
               Portable & Modular
                      Take only what you need!
               Used in most other languages
                      Tried and tested; stick to what we’re used to




© SitePen, Inc. All Rights Reserved
Key Class Components

               Constructor
                      Fires upon instance creation
               Properties or “Options”
                      Configures an instance’s behavior
               Methods
                      Accomplish tasks within the instance




© SitePen, Inc. All Rights Reserved
Key Class Concepts

               Extending
                      Builds upon existing classes for more goal-specific behavior
                      Uses the existing class’ prototype as its base
                      DON’T REPEAT YOURSELF
               Implementing and “monkey patching”
                      Add or modify behavior on existing objects via prototype mod.
                      May keep reference to original method and call anywhere within
                      the replacing method
               Lots of methods and options
                      Makes extending much, much easier!



© SitePen, Inc. All Rights Reserved
Dojo & MooTools Class Similarities

               Both use prototypal inheritance
                      Objects are provided another object as its prototype
                      jQuery, in contrast, is a “functional” lib
               Both provide an easy interface for creating complex classes
               Both provide methods for calling a parent class’ method of
               the same name
               Both are extremely modular




© SitePen, Inc. All Rights Reserved
JavaScript Prototypal Inheritance

      //      Crockford’s latest implementation

      // If Object.create isn’t supported by the browser...
      if (typeof Object.create !== 'function') {
          // Implement it!
          Object.create = function (proto) {
              function F() {}
              F.prototype = proto;
              return new F();
          };
      }
      var newObject = Object.create(oldObject);

      // Use the new class
      var myInstance = new newObject({ /* props */ });


      //      Available:              http://javascript.crockford.com/prototypal.html




© SitePen, Inc. All Rights Reserved
MooTools’ Class

               Class is a standard MooTools module; creates a new “class”
               Accepts one argument: an object with key/value methods and
               properties
               Detects predetermined, “special” property names to manage
               class creation and dependencies
               Returns the newly created class
               Adds additional methods to each class
                      toElement
                      implement




© SitePen, Inc. All Rights Reserved
MooTools’ Class: Special Properties

               Extends
                      The existing class which the new class should extend
               Implements
                      An array of existing classes to be mixed in
               initialize
                      The class constructor
                      Varies in signature depending on required arguments to create an
                      instance of the class
                      Last argument is usually an options object with instance-specific
                      properties



© SitePen, Inc. All Rights Reserved
MooTools Class Structure

      // Declare the new Class
      var MyClassName = new Class({
        // Extends an existing class;    use as base prototype
        Extends: SomeExistingClass,

          // Mix in properties from these classes/objects as well
          Implements: [Options, Events],

          // Default options list
          options: {
             myOpt: true
          },

          // Constructor
          initialize: function(someElement, options) {
             this.setOptions(options);
             this.someElement = document.id(someElement); // Accepts IDs or Nodes
          },

        // Some class method
        utilityMethod: function(arg1, arg2) {
          this.parent(arg1, arg2);
          this.fireEvent('complete');
        }
      });


© SitePen, Inc. All Rights Reserved
(prepare yourself for
             the worse now)


© SitePen, Inc. All Rights Reserved
Inline Slideshow - No Class

      window.addEvent('domready',function() {
        // Settings
        var showDuration = 3000;
        var container = $('slideshow-container');
        var images = container.getElements('img');
        var currentIndex = 0;
        var interval;
        // Opacity and fade
        images.each(function(img,i){
           if(i > 0) {
             img.set('opacity',0);
           }
        });
        // The “Worker”
        var show = function() {
           images[currentIndex].fade('out');
           images[currentIndex = currentIndex < images.length - 1 ? currentIndex+1 :
      0].fade('in');
        };
        // Start once the page is finished loading
        window.addEvent('load',function(){
           interval = show.periodical(showDuration);
        });
      });



© SitePen, Inc. All Rights Reserved
Classy Slideshow

      var SimpleSlideshow = new Class({
        options: {
           showDuration: 3000
        },
        Implements: [Options, Events],
        currentIndex: 0,
        initialize: function(container, elements, options) {
           //settings
           this.container = $(container);
           this.elements = $$(elements);
           this.setOptions(options);
           // ....
      }
        show: function(to) { /* fade in/out logic */ },
        start: function() { /* interval logic */ },
        stop: function() { /* clear interval logic */ },
      // more methods...
      });

      // Using the class....
      var show = new SimpleSlideshow('slideshow', 'img', {
          showDuration: 2000
      });
      show.start();



© SitePen, Inc. All Rights Reserved
Sample MooTools Class: Request.Twitter

      // Declare the new Class
      Request.Twitter = new Class({
        // Extends an existing class; use as base prototype
        Extends: Request.JSONP,
        // Create a list of options
        Implements: [Linkify],
        // Provide the default options
        options: {
           url: "http://twitter.com/statuses/user_timeline/{term}.json",
           data: { count: 5 }
        },
        // Constructor
        initialize: function(term, options) {
           this.parent(options); // pass options to “parent” class
           this.options.url = this.options.url.substitute({ term: term });
        },
        // Success Event
        success: function(data, script) {
           data[0].each(function(tweet) {
             tweet.text = this.linkify(tweet.text);
           }, this);
           this.parent(data, script);
        }
      });



© SitePen, Inc. All Rights Reserved
Sample MooTools Class: Request.Twitter (c...)

      (function() {

          // Create a new instance
          var request = new Request.Twitter("davidwalshblog", {
            // Customize an options:
            data: { count: 20 }, // Load 20 tweets instead of the default 5
            // When the request succeeds...
            onComplete: function(tweets) {
              console.warn("Tweet received: ", tweets);
            }
          });

          // Send a request for tweets
          request.send();

      })();




© SitePen, Inc. All Rights Reserved
Sample MooTools Class: implement()

      // Extend the existing class’ prototype with properties or methods
      MyExistingClass.implement({
        // Basic property
        isMental: true,
        // New method!
        someNewMethod: function() {
          // Do some new stuff in here
        }
      });

      // A realistic usage
      Request.Twitter.implement({
        // Linkifies the a tweet!
        linkify: function(text) {
          return text.replace(/(https?://[w-:;?&=+.%#/]+)/gi, '<a href="$1">$1</a>')
          .replace(/(^|W)@(w+)/g, '$1<a href="http://twitter.com/$2">@$2</a>')
          .replace(/(^|W)#(w+)/g, '$1#<a href="http://search.twitter.com/search?q=
      %23$2">$2</a>');
        }
      });




© SitePen, Inc. All Rights Reserved
Classes with Dojo: dojo.declare

               dojo.declare creates Dojo classes
                      Traditional class creation methods since Dojo 0.x
                      Dojo 1.6+ uses AMD format for
               Accepts 3 arguments:
                      Class name with namespace
                      null, single class, or an array of inheritance, if any
                            First object in array is the extender
                            Subsequent objects act as mixins
                      Object with methods and properties with default values
               Adds several additional properties and methods to each class


© SitePen, Inc. All Rights Reserved
Dojo’s dojo.declare: Special Properties

               constructor
                      The class constructor
                      Varies in signature depending on required arguments to create an
                      instance of the class
                      Last argument is usually an options object with instance-specific
                      properties
                      Automatically fired up the inheritance chain
               Dijit’s _Widget and _Templated provides additional
               special methods for UI widgets
                      postMixInProperties, postCreate, startup




© SitePen, Inc. All Rights Reserved
Dojo Class Structure

      // Provide the class
      dojo.provide('mynamespace.ResourceName');

      // Require the class dependencies
      dojo.require('dojo.resource1');
      dojo.require('dojo.resource2');

      // Declare the new class with dojo.resources1 as the base prototype, 2 as a mixin
      dojo.declare('mynamespace.ResourceName', [dojo.resource1, dojo.resource2], {

          // Add a custom property
          age: 10,

          // Constructor to do something
          constructor: function(args) {
             this.dogAge = (args.age || this.age) * 7;
          },

        // Add a custom method
        overridenMethod: function(arg1) {
          // Call parent method
          this.inherited(arguments);
        }
      });



© SitePen, Inc. All Rights Reserved
Dojo Class Structure: Usage

      // Require the class
      dojo.require('mynamespace.ResourceName');

      // Create an instance and work with it!
      var myInstance = new mynamespace.ResourceName({
          age: 20
      });

      myInstance.doSomething();

      myInstance.doSomethingElse();




© SitePen, Inc. All Rights Reserved
Sample Dojo Class: dojo.Stateful

      dojo.provide("dojo.Stateful");
      // Declare the class
      dojo.declare("dojo.Stateful", null, {
        postscript: function(mixin){
           if(mixin){
             dojo.mixin(this, mixin);
           }
        },
        get: function(/*String*/name){
           return this[name];
        },
        set: function(/*String*/name, /*Object*/value){
           if(typeof name === "object"){
             for(var x in name){
               this.set(x, name[x]);
             }
             return this;
           }
           var oldValue = this[name];
           this[name] = value;
           if(this._watchCallbacks){
             this._watchCallbacks(name, oldValue, value);
           }
           return this;
        },


© SitePen, Inc. All Rights Reserved
Sample Dojo Class: dojo.Stateful continued...
    watch: function(/*String?*/name, /*Function*/callback){
        var callbacks = this._watchCallbacks;
        if(!callbacks){
           var self = this;
           callbacks = this._watchCallbacks = function(name, oldValue, value, ignoreCatchall){
             var notify = function(propertyCallbacks){
                for(var i = 0, l = propertyCallbacks && propertyCallbacks.length; i < l; i++){
                  try{
                    propertyCallbacks[i].call(self, name, oldValue, value);
                  }catch(e){
                    console.error(e);
                  }
                }
             };
             notify(callbacks[name]);
             if(!ignoreCatchall){
                notify(callbacks["*"]); // the catch-all
             }
           }; // we use a function instead of an object so it will be ignored by JSON conversion
        }
        if(!callback && typeof name === "function"){
           callback = name;
           name = "*";
        }
        var propertyCallbacks = callbacks[name];
        if(typeof propertyCallbacks !== "object"){
           propertyCallbacks = callbacks[name] = [];
        }
        propertyCallbacks.push(callback);
        return {
           unwatch: function(){
             propertyCallbacks.splice(dojo.indexOf(propertyCallbacks, callback), 1);
           }
        };
      }
© SitePen, Inc. All Rights Reserved
dojo.extend

      // Require the resource
      dojo.require("dojo.Deferred");

      // Add new properties and functions to the dojo.Deferred prototype
      dojo.extend(dojo.Deferred, {
        addCallback: function (/*Function*/callback) {
           return this.addCallbacks(dojo.hitch.apply(dojo, arguments));
        },

          addErrback: function (/*Function*/errback) {
             return this.addCallbacks(null, dojo.hitch.apply(dojo, arguments));
          },

        addBoth: function (/*Function*/callback) {
           var enclosed = dojo.hitch.apply(dojo, arguments);
           return this.addCallbacks(enclosed, enclosed);
        },
        fired: -1
      });




© SitePen, Inc. All Rights Reserved
Sample Dojo Class: AMD

      define([
         "dojo/_base/declare",
         "./ValidationTextBox",
         "./ComboBoxMixin"
         ], function(declare, ValidationTextBox, ComboBoxMixin){

             return declare("dojo/_base/declare", [ValidationTextBox, ComboBoxMixin], {

                    // Add more properties and methods here



             }
      });




© SitePen, Inc. All Rights Reserved
Dojo & MooTools Class Differences

               Dojo provides a custom loader
                      Retrieve resources (classes, templates, resources, ...) dynamically
                            Uses synchronous XHR requests
                            Easier for “change and refresh” development
                            Cross-domain loading even works great!
                      MooTools provides no loader, but a builder is available
               Namespacing
                      Dojo is built to work with namespaces
                      MooTools-provided classes are global, and are not placed in
                      namespaces unless specified otherwise




© SitePen, Inc. All Rights Reserved
Tips for Creating Classes

               Make your utility classes flexible
                      Easier to use from project to project
               Use meaningful property and method names
                      Allows for ease in development, both inside the class and out
               Stick with the toolkit’s coding style
                      Spacinging, naming, structure, namespacing
               Use lots of methods
                      Allows for easier extension and customization




© SitePen, Inc. All Rights Reserved
Finding and Sharing Classes

               MooTools Forge
                      Massive repository of MooTools classes
                      Class types include Fx, Interface, Media, Request, Utilities, and
                      more!
                      Several available on David Walsh Blog
               DojoX
                      Dojo’s official “plugin” division
                      Features many enterprise-quality sub-libraries, like GFX, Charting
                      Features “enhancers” for existing Dojo and Dijit classes
                      No official public, user-driven plugin repository...yet



© SitePen, Inc. All Rights Reserved
Stay Classy!

               There’s more to JavaScript than j(ust)querying for DOM
               nodes, creating animations, and making simple AJAX requests
               JavaScript class structures allow for ALL types of task
               management, not just DOM node-related tasks
               Consistent, coherent class APIs allow for faster, flexible
               development regardless of task




© SitePen, Inc. All Rights Reserved

Mais conteúdo relacionado

Mais procurados

13 java beans
13 java beans13 java beans
13 java beanssnopteck
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsLalit Kale
 
Reusable Ruby • Rt 9 Ruby Group • Jun 2012
Reusable Ruby • Rt 9 Ruby Group • Jun 2012Reusable Ruby • Rt 9 Ruby Group • Jun 2012
Reusable Ruby • Rt 9 Ruby Group • Jun 2012skinandbones
 
Top 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersTop 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersWhizlabs
 
Learn java
Learn javaLearn java
Learn javaPalahuja
 
developing sysadmin, sysadmining developersGuug devops puppet
developing sysadmin, sysadmining developersGuug devops puppetdeveloping sysadmin, sysadmining developersGuug devops puppet
developing sysadmin, sysadmining developersGuug devops puppetMartin Alfke
 
JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)Prof. Erwin Globio
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternNishith Shukla
 
The 23 gof design patterns in java ,the summary
The 23 gof design patterns in java ,the summaryThe 23 gof design patterns in java ,the summary
The 23 gof design patterns in java ,the summaryguestebd714
 

Mais procurados (20)

Javabeans
JavabeansJavabeans
Javabeans
 
Basic java part_ii
Basic java part_iiBasic java part_ii
Basic java part_ii
 
13 java beans
13 java beans13 java beans
13 java beans
 
Java beans
Java beansJava beans
Java beans
 
Puppet quick start guide
Puppet quick start guidePuppet quick start guide
Puppet quick start guide
 
Unit iv
Unit ivUnit iv
Unit iv
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
Java basic
Java basicJava basic
Java basic
 
Reusable Ruby • Rt 9 Ruby Group • Jun 2012
Reusable Ruby • Rt 9 Ruby Group • Jun 2012Reusable Ruby • Rt 9 Ruby Group • Jun 2012
Reusable Ruby • Rt 9 Ruby Group • Jun 2012
 
Dacj 2-2 a
Dacj 2-2 aDacj 2-2 a
Dacj 2-2 a
 
intellimeet
intellimeetintellimeet
intellimeet
 
Top 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersTop 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed Answers
 
Learn java
Learn javaLearn java
Learn java
 
developing sysadmin, sysadmining developersGuug devops puppet
developing sysadmin, sysadmining developersGuug devops puppetdeveloping sysadmin, sysadmining developersGuug devops puppet
developing sysadmin, sysadmining developersGuug devops puppet
 
JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
 
B.Sc. III(VI Sem) Advance Java Unit2: Appet
B.Sc. III(VI Sem) Advance Java Unit2: AppetB.Sc. III(VI Sem) Advance Java Unit2: Appet
B.Sc. III(VI Sem) Advance Java Unit2: Appet
 
Effective Java
Effective JavaEffective Java
Effective Java
 
The 23 gof design patterns in java ,the summary
The 23 gof design patterns in java ,the summaryThe 23 gof design patterns in java ,the summary
The 23 gof design patterns in java ,the summary
 
BeJUG JavaFx In Practice
BeJUG JavaFx In PracticeBeJUG JavaFx In Practice
BeJUG JavaFx In Practice
 

Semelhante a JavaScript Coding with Class

Jquery Plugin
Jquery PluginJquery Plugin
Jquery PluginRavi Mone
 
Javascript for the c# developer
Javascript for the c# developerJavascript for the c# developer
Javascript for the c# developerSalvatore Fazio
 
java beans
java beansjava beans
java beanslapa
 
(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHP(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHPRick Ogden
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010Rich Helton
 
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application FrameworkJady Yang
 
Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Savio Sebastian
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Alena Holligan
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming ConceptsBhushan Nagaraj
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Arsen Gasparyan
 
Javascript fundamentals and not
Javascript fundamentals and notJavascript fundamentals and not
Javascript fundamentals and notSalvatore Fazio
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsMohammad Shaker
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascriptUsman Mehmood
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptDonald Sipe
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to JavaSMIJava
 

Semelhante a JavaScript Coding with Class (20)

Jquery Plugin
Jquery PluginJquery Plugin
Jquery Plugin
 
Javascript for the c# developer
Javascript for the c# developerJavascript for the c# developer
Javascript for the c# developer
 
java beans
java beansjava beans
java beans
 
(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHP(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHP
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application Framework
 
Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2
 
ClassJS
ClassJSClassJS
ClassJS
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
 
Javascript fundamentals and not
Javascript fundamentals and notJavascript fundamentals and not
Javascript fundamentals and not
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
 

Último

SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 

Último (20)

SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

JavaScript Coding with Class

  • 1. JavaScript Coding with Class © SitePen, Inc. All Rights Reserved
  • 2. Who is David Walsh? Software Engineer for SitePen MooTools Team Member - Add real photo of me David Walsh Blog scribe - Slide in caricature Script & Style founder 10 years working experience @davidwalshblog © SitePen, Inc. All Rights Reserved
  • 3. Class? Class patterns As featured in most programming languages Object-oriented methodology employed Beautiful code .... a.k.a. programmer porn Adheres to basic JavaScript coding practices © SitePen, Inc. All Rights Reserved
  • 4. Class...from a Yank? © SitePen, Inc. All Rights Reserved
  • 5. (not class) © SitePen, Inc. All Rights Reserved
  • 6. (class) © SitePen, Inc. All Rights Reserved
  • 7. (not class) Add photo of: - Jordon - Boy George © SitePen, Inc. All Rights Reserved
  • 8. (class) © SitePen, Inc. All Rights Reserved
  • 9. Classes in JavaScript True “classes” are not provided by JavaScript ....even though class is a reserved word Enclosure patterns, functions, and their prototypes are used to simulate classes Toolkits like Dojo and MooTools abstract those patterns to allow developers to create powerful, flexible classes © SitePen, Inc. All Rights Reserved
  • 10. Why Classes? Easier to read, understand, & maintain Unified API despite type of task Inheritance Patterns Easy to extend “Don’t Repeat Yourself” philosophy employed Portable & Modular Take only what you need! Used in most other languages Tried and tested; stick to what we’re used to © SitePen, Inc. All Rights Reserved
  • 11. Key Class Components Constructor Fires upon instance creation Properties or “Options” Configures an instance’s behavior Methods Accomplish tasks within the instance © SitePen, Inc. All Rights Reserved
  • 12. Key Class Concepts Extending Builds upon existing classes for more goal-specific behavior Uses the existing class’ prototype as its base DON’T REPEAT YOURSELF Implementing and “monkey patching” Add or modify behavior on existing objects via prototype mod. May keep reference to original method and call anywhere within the replacing method Lots of methods and options Makes extending much, much easier! © SitePen, Inc. All Rights Reserved
  • 13. Dojo & MooTools Class Similarities Both use prototypal inheritance Objects are provided another object as its prototype jQuery, in contrast, is a “functional” lib Both provide an easy interface for creating complex classes Both provide methods for calling a parent class’ method of the same name Both are extremely modular © SitePen, Inc. All Rights Reserved
  • 14. JavaScript Prototypal Inheritance // Crockford’s latest implementation // If Object.create isn’t supported by the browser... if (typeof Object.create !== 'function') { // Implement it! Object.create = function (proto) { function F() {} F.prototype = proto; return new F(); }; } var newObject = Object.create(oldObject); // Use the new class var myInstance = new newObject({ /* props */ }); // Available: http://javascript.crockford.com/prototypal.html © SitePen, Inc. All Rights Reserved
  • 15. MooTools’ Class Class is a standard MooTools module; creates a new “class” Accepts one argument: an object with key/value methods and properties Detects predetermined, “special” property names to manage class creation and dependencies Returns the newly created class Adds additional methods to each class toElement implement © SitePen, Inc. All Rights Reserved
  • 16. MooTools’ Class: Special Properties Extends The existing class which the new class should extend Implements An array of existing classes to be mixed in initialize The class constructor Varies in signature depending on required arguments to create an instance of the class Last argument is usually an options object with instance-specific properties © SitePen, Inc. All Rights Reserved
  • 17. MooTools Class Structure // Declare the new Class var MyClassName = new Class({ // Extends an existing class; use as base prototype Extends: SomeExistingClass, // Mix in properties from these classes/objects as well Implements: [Options, Events], // Default options list options: { myOpt: true }, // Constructor initialize: function(someElement, options) { this.setOptions(options); this.someElement = document.id(someElement); // Accepts IDs or Nodes }, // Some class method utilityMethod: function(arg1, arg2) { this.parent(arg1, arg2); this.fireEvent('complete'); } }); © SitePen, Inc. All Rights Reserved
  • 18. (prepare yourself for the worse now) © SitePen, Inc. All Rights Reserved
  • 19. Inline Slideshow - No Class window.addEvent('domready',function() { // Settings var showDuration = 3000; var container = $('slideshow-container'); var images = container.getElements('img'); var currentIndex = 0; var interval; // Opacity and fade images.each(function(img,i){ if(i > 0) { img.set('opacity',0); } }); // The “Worker” var show = function() { images[currentIndex].fade('out'); images[currentIndex = currentIndex < images.length - 1 ? currentIndex+1 : 0].fade('in'); }; // Start once the page is finished loading window.addEvent('load',function(){ interval = show.periodical(showDuration); }); }); © SitePen, Inc. All Rights Reserved
  • 20. Classy Slideshow var SimpleSlideshow = new Class({ options: { showDuration: 3000 }, Implements: [Options, Events], currentIndex: 0, initialize: function(container, elements, options) { //settings this.container = $(container); this.elements = $$(elements); this.setOptions(options); // .... } show: function(to) { /* fade in/out logic */ }, start: function() { /* interval logic */ }, stop: function() { /* clear interval logic */ }, // more methods... }); // Using the class.... var show = new SimpleSlideshow('slideshow', 'img', { showDuration: 2000 }); show.start(); © SitePen, Inc. All Rights Reserved
  • 21. Sample MooTools Class: Request.Twitter // Declare the new Class Request.Twitter = new Class({ // Extends an existing class; use as base prototype Extends: Request.JSONP, // Create a list of options Implements: [Linkify], // Provide the default options options: { url: "http://twitter.com/statuses/user_timeline/{term}.json", data: { count: 5 } }, // Constructor initialize: function(term, options) { this.parent(options); // pass options to “parent” class this.options.url = this.options.url.substitute({ term: term }); }, // Success Event success: function(data, script) { data[0].each(function(tweet) { tweet.text = this.linkify(tweet.text); }, this); this.parent(data, script); } }); © SitePen, Inc. All Rights Reserved
  • 22. Sample MooTools Class: Request.Twitter (c...) (function() { // Create a new instance var request = new Request.Twitter("davidwalshblog", { // Customize an options: data: { count: 20 }, // Load 20 tweets instead of the default 5 // When the request succeeds... onComplete: function(tweets) { console.warn("Tweet received: ", tweets); } }); // Send a request for tweets request.send(); })(); © SitePen, Inc. All Rights Reserved
  • 23. Sample MooTools Class: implement() // Extend the existing class’ prototype with properties or methods MyExistingClass.implement({ // Basic property isMental: true, // New method! someNewMethod: function() { // Do some new stuff in here } }); // A realistic usage Request.Twitter.implement({ // Linkifies the a tweet! linkify: function(text) { return text.replace(/(https?://[w-:;?&=+.%#/]+)/gi, '<a href="$1">$1</a>') .replace(/(^|W)@(w+)/g, '$1<a href="http://twitter.com/$2">@$2</a>') .replace(/(^|W)#(w+)/g, '$1#<a href="http://search.twitter.com/search?q= %23$2">$2</a>'); } }); © SitePen, Inc. All Rights Reserved
  • 24. Classes with Dojo: dojo.declare dojo.declare creates Dojo classes Traditional class creation methods since Dojo 0.x Dojo 1.6+ uses AMD format for Accepts 3 arguments: Class name with namespace null, single class, or an array of inheritance, if any First object in array is the extender Subsequent objects act as mixins Object with methods and properties with default values Adds several additional properties and methods to each class © SitePen, Inc. All Rights Reserved
  • 25. Dojo’s dojo.declare: Special Properties constructor The class constructor Varies in signature depending on required arguments to create an instance of the class Last argument is usually an options object with instance-specific properties Automatically fired up the inheritance chain Dijit’s _Widget and _Templated provides additional special methods for UI widgets postMixInProperties, postCreate, startup © SitePen, Inc. All Rights Reserved
  • 26. Dojo Class Structure // Provide the class dojo.provide('mynamespace.ResourceName'); // Require the class dependencies dojo.require('dojo.resource1'); dojo.require('dojo.resource2'); // Declare the new class with dojo.resources1 as the base prototype, 2 as a mixin dojo.declare('mynamespace.ResourceName', [dojo.resource1, dojo.resource2], { // Add a custom property age: 10, // Constructor to do something constructor: function(args) { this.dogAge = (args.age || this.age) * 7; }, // Add a custom method overridenMethod: function(arg1) { // Call parent method this.inherited(arguments); } }); © SitePen, Inc. All Rights Reserved
  • 27. Dojo Class Structure: Usage // Require the class dojo.require('mynamespace.ResourceName'); // Create an instance and work with it! var myInstance = new mynamespace.ResourceName({ age: 20 }); myInstance.doSomething(); myInstance.doSomethingElse(); © SitePen, Inc. All Rights Reserved
  • 28. Sample Dojo Class: dojo.Stateful dojo.provide("dojo.Stateful"); // Declare the class dojo.declare("dojo.Stateful", null, { postscript: function(mixin){ if(mixin){ dojo.mixin(this, mixin); } }, get: function(/*String*/name){ return this[name]; }, set: function(/*String*/name, /*Object*/value){ if(typeof name === "object"){ for(var x in name){ this.set(x, name[x]); } return this; } var oldValue = this[name]; this[name] = value; if(this._watchCallbacks){ this._watchCallbacks(name, oldValue, value); } return this; }, © SitePen, Inc. All Rights Reserved
  • 29. Sample Dojo Class: dojo.Stateful continued... watch: function(/*String?*/name, /*Function*/callback){ var callbacks = this._watchCallbacks; if(!callbacks){ var self = this; callbacks = this._watchCallbacks = function(name, oldValue, value, ignoreCatchall){ var notify = function(propertyCallbacks){ for(var i = 0, l = propertyCallbacks && propertyCallbacks.length; i < l; i++){ try{ propertyCallbacks[i].call(self, name, oldValue, value); }catch(e){ console.error(e); } } }; notify(callbacks[name]); if(!ignoreCatchall){ notify(callbacks["*"]); // the catch-all } }; // we use a function instead of an object so it will be ignored by JSON conversion } if(!callback && typeof name === "function"){ callback = name; name = "*"; } var propertyCallbacks = callbacks[name]; if(typeof propertyCallbacks !== "object"){ propertyCallbacks = callbacks[name] = []; } propertyCallbacks.push(callback); return { unwatch: function(){ propertyCallbacks.splice(dojo.indexOf(propertyCallbacks, callback), 1); } }; } © SitePen, Inc. All Rights Reserved
  • 30. dojo.extend // Require the resource dojo.require("dojo.Deferred"); // Add new properties and functions to the dojo.Deferred prototype dojo.extend(dojo.Deferred, { addCallback: function (/*Function*/callback) { return this.addCallbacks(dojo.hitch.apply(dojo, arguments)); }, addErrback: function (/*Function*/errback) { return this.addCallbacks(null, dojo.hitch.apply(dojo, arguments)); }, addBoth: function (/*Function*/callback) { var enclosed = dojo.hitch.apply(dojo, arguments); return this.addCallbacks(enclosed, enclosed); }, fired: -1 }); © SitePen, Inc. All Rights Reserved
  • 31. Sample Dojo Class: AMD define([ "dojo/_base/declare", "./ValidationTextBox", "./ComboBoxMixin" ], function(declare, ValidationTextBox, ComboBoxMixin){ return declare("dojo/_base/declare", [ValidationTextBox, ComboBoxMixin], { // Add more properties and methods here } }); © SitePen, Inc. All Rights Reserved
  • 32. Dojo & MooTools Class Differences Dojo provides a custom loader Retrieve resources (classes, templates, resources, ...) dynamically Uses synchronous XHR requests Easier for “change and refresh” development Cross-domain loading even works great! MooTools provides no loader, but a builder is available Namespacing Dojo is built to work with namespaces MooTools-provided classes are global, and are not placed in namespaces unless specified otherwise © SitePen, Inc. All Rights Reserved
  • 33. Tips for Creating Classes Make your utility classes flexible Easier to use from project to project Use meaningful property and method names Allows for ease in development, both inside the class and out Stick with the toolkit’s coding style Spacinging, naming, structure, namespacing Use lots of methods Allows for easier extension and customization © SitePen, Inc. All Rights Reserved
  • 34. Finding and Sharing Classes MooTools Forge Massive repository of MooTools classes Class types include Fx, Interface, Media, Request, Utilities, and more! Several available on David Walsh Blog DojoX Dojo’s official “plugin” division Features many enterprise-quality sub-libraries, like GFX, Charting Features “enhancers” for existing Dojo and Dijit classes No official public, user-driven plugin repository...yet © SitePen, Inc. All Rights Reserved
  • 35. Stay Classy! There’s more to JavaScript than j(ust)querying for DOM nodes, creating animations, and making simple AJAX requests JavaScript class structures allow for ALL types of task management, not just DOM node-related tasks Consistent, coherent class APIs allow for faster, flexible development regardless of task © SitePen, Inc. All Rights Reserved

Notas do Editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. &amp;#x201C;There are three boobs on this slide; should have put one over Piers&amp;#x2019; face&amp;#x201D;\n\n&amp;#x201C;Oh hey, I missed a boob on this slide&amp;#x201D;\n
  8. \n
  9. \n
  10. Say that there are exceptions to every rule, and it&amp;#x2019;s up to the developers to make each of the above true.\n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n