SlideShare ist ein Scribd-Unternehmen logo
1 von 46
Downloaden Sie, um offline zu lesen
Programming To
   Patterns
How I used to write
How I used to write

        Classes
        DatePicker
       FormValidator
             Fx
          Request
         Slideshow
            etc...
How I used to write
var myApp = {
  init: function(){
   myApp.apples()                                         Classes
   myApp.orange()                                         DatePicker
   myApp.lemons()                                        FormValidator
 },                                                            Fx
 apples: function(){                                        Request
   $$(‘div.apple’).each(function(apple) {                  Slideshow
      var form = apple.getElement(‘form’);                    etc...
      form.addEvent(‘submit’, funciton(event){ ....});
   });
 },
 orange: function(){
   $(‘orange’).getElements(‘li’).each...
 },
  etc...
How I used to write
var myApp = {
  init: function(){
   myApp.apples()                                         Classes
   myApp.orange()                                         DatePicker
   myApp.lemons()                                        FormValidator
 },                                                            Fx
 apples: function(){                                        Request
   $$(‘div.apple’).each(function(apple) {                  Slideshow
      var form = apple.getElement(‘form’);                    etc...
      form.addEvent(‘submit’, funciton(event){ ....});
   });
 },
 orange: function(){
   $(‘orange’).getElements(‘li’).each...
 },
  etc...


                       This tends to get out of hand
Banging it out...
<script>
window.addEvent(‘domready’, function(){
 $(‘myForm’).addEvent(‘submit’, function(evt){
      evt.preventDefault();
      this.send({
       onComplete: function(result){ ... },
       update: $(‘myContainer’)
      });
 });
});
</script>


       This is very tempting.
Pros
• Writing the logic for a specific app is fast
  and furious

• The test environment is the app
Pros
• Writing the logic for a specific app is fast
  and furious

• The test environment is the app
                 & Cons
• It’s much harder to maintain
• A high percentage of code you write for the
 app isn’t reusable
Using Classes
Using Classes
  This is how
MooTools does it
var Human = new Class({
    isAlive: true,
    energy: 1,
    eat: function(){
        this.energy++;
    }
});




                          Human
Using Classes
  This is how
MooTools does it
var Human = new Class({
    isAlive: true,
    energy: 1,
    eat: function(){
        this.energy++;
    }
});


var bob = new Human();
//bob.energy === 1

bob.eat();
//bob.energy === 2




                          Human




                                     bob
Extending Classes
Extending Classes
var Human = new Class({
    initialize: function(name, age){
        this.name = name;
        this.age = age;
    },
    isAlive: true,
    energy: 1,
    eat: function(){
        this.energy++;
    }
});
Extending Classes
var Human = new Class({                var Ninja = new Class({
    initialize: function(name, age){     Extends: Human,
        this.name = name;                initialize: function(side, name, age){
        this.age = age;                     this.side = side;
    },                                      this.parent(name, age);
    isAlive: true,                       },
    energy: 1,                           energy: 100,
    eat: function(){                     attack: function(target){
        this.energy++;                      this.energy = this.energy - 5;
    }                                       target.isAlive = false;
});                                      }
                                       });
Extending Classes
var Human = new Class({                var Ninja = new Class({
    initialize: function(name, age){     Extends: Human,
        this.name = name;                initialize: function(side, name, age){
        this.age = age;                     this.side = side;
    },                                      this.parent(name, age);
    isAlive: true,                       },
    energy: 1,                           energy: 100,
    eat: function(){                     attack: function(target){
        this.energy++;                      this.energy = this.energy - 5;
    }                                       target.isAlive = false;
});                                      }
                                       });
Extending Classes
var Human = new Class({                      var Ninja = new Class({
    initialize: function(name, age){           Extends: Human,
        this.name = name;                      initialize: function(side, name, age){
        this.age = age;                           this.side = side;
    },                                            this.parent(name, age);
    isAlive: true,                             },
    energy: 1,                                 energy: 100,
    eat: function(){                           attack: function(target){
        this.energy++;                            this.energy = this.energy - 5;
    }                                             target.isAlive = false;
});                                            }
                                             });


                           var bob = new Human('Bob', 25);
Extending Classes
var Human = new Class({                      var Ninja = new Class({
    initialize: function(name, age){           Extends: Human,
        this.name = name;                      initialize: function(side, name, age){
        this.age = age;                           this.side = side;
    },                                            this.parent(name, age);
    isAlive: true,                             },
    energy: 1,                                 energy: 100,
    eat: function(){                           attack: function(target){
        this.energy++;                            this.energy = this.energy - 5;
    }                                             target.isAlive = false;
});                                            }
                                             });


                           var bob = new Human('Bob', 25);


                          var blackNinja =
                            new Ninja('evil', 'Nin Tendo', 'unknown');
                          //blackNinja.isAlive = true
                          //blackNinja.name = 'Nin Tendo'

                          blackNinja.attack(bob);
                          //bob never had a chance
Implementing Classes
Implementing Classes
var Human = new Class({
  initialize: function(name, age){
     this.name = name;
     this.age = age;
  },
  isAlive: true,
  energy: 1,
  eat: function(){
     this.energy++;
  }
});
Implementing Classes
var Human = new Class({
  initialize: function(name, age){
     this.name = name;
     this.age = age;
  },
  isAlive: true,
  energy: 1,
  eat: function(){
     this.energy++;
  }
});

var Warrior = new Class({
  energy: 100,
  kills: 0,
  attack: function(target){
    if (target.energy < this.energy) {
       target.isAlive = false;
       this.kills++;
    }
    this.energy = this.energy - 5;
  }
});
Implementing Classes
var Human = new Class({                  var Ninja = new Class({
  initialize: function(name, age){         Extends: Human,
     this.name = name;                     Implements: [Warrior],
     this.age = age;                       initialize: function(side, name, age){
  },                                         this.side = side;
  isAlive: true,                             this.parent(name, age);
  energy: 1,                               }
  eat: function(){                       });
     this.energy++;
  }
});

var Warrior = new Class({                var Samurai = new Class({
  energy: 100,                             Extends: Human,
  kills: 0,                                Implements: [Warrior],
  attack: function(target){                side: 'good',
    if (target.energy < this.energy) {     energy: 1000
       target.isAlive = false;           });
       this.kills++;
    }
    this.energy = this.energy - 5;
  }
});
When to write a class...
When to write a class...
When to write a class...
When to write a class...
When to write a class...
Key Aspects of JS Classes
Key Aspects of JS Classes
• Shallow inheritance works best.
Key Aspects of JS Classes
• Shallow inheritance works best.
• Break up logic into small methods.
Key Aspects of JS Classes
• Shallow inheritance works best.
• Break up logic into small methods.
• Break up functionality into small classes.
Key Aspects of JS Classes
• Shallow inheritance works best.
• Break up logic into small methods.
• Break up functionality into small classes.
• Build ‘controller’ classes for grouped
 functionality.
Key Aspects of JS Classes
• Shallow inheritance works best.
• Break up logic into small methods.
• Break up functionality into small classes.
• Build ‘controller’ classes for grouped
 functionality.

• Use options and events liberally.
Key Aspects of JS Classes
• Shallow inheritance works best.
• Break up logic into small methods.
• Break up functionality into small classes.
• Build ‘controller’ classes for grouped
  functionality.

• Use options and events liberally.
• Don’t be afraid to refactor, but avoid
  breaking the interface.
Let’s look at that earlier example again
...
<script>
$(‘myForm’).addEvent(‘submit’, function(evt){
  evt.preventDefault();
  this.send({
      onComplete: function(result){ ... },
      update: $(‘myContainer’)
  });
});
</script>
Program a Pattern
var FormUpdater = new Class({
  initialize: function(form, container, options) {
    this.form = $(form);
    this.container = $(container);
    this.request = new Request(options);
    this.attach();
  },
  attach: function(){
    this.form.addEvent(‘submit’,
      this.send.bind(this));
  },
  send: function(evt){
    if (evt) evt.preventDefault();
    this.request.send({
      url: this.form.get(‘action’),
      onComplete: this.onComplete.bind(this)
    });
  },
  onComplete: function(responseTxt){
      this.container.set(‘html’, responseTxt);
  }
});
new FormUpdater($(‘myForm’), $(‘myContainer’));
...and then extend it
var FormUpdater.Append = new Class({
 Extends: FormUpdater,
 onComplete: function(responseTxt){
    this.container.adopt(
      new Element(‘div’, {html: responseTxt})
    );
 }
});
new FormUpdater.Append($(‘myForm’), $(‘myTarget’));
How I write now
How I write now
var myApp = {
  init: function(){
   myApp.apples()                      Classes
   myApp.orange()                      DatePicker
   myApp.lemons()                     FormValidator
 },                                         Fx
 apples: function(){                     Request
   new AppleGroup($$(‘div.apple’));     Slideshow
 },                                       Apple
 orange: function(){                   AppleGroup
   new Orange($(‘orange’)                Orange
 },                                        etc...
  etc...
How I write now
var myApp = {
  init: function(){
   myApp.apples()                              Classes
   myApp.orange()                             DatePicker
   myApp.lemons()                            FormValidator
 },                                                Fx
 apples: function(){                            Request
   new AppleGroup($$(‘div.apple’));            Slideshow
 },                                              Apple
 orange: function(){                          AppleGroup
   new Orange($(‘orange’)                       Orange
 },                                               etc...
  etc...




                  I write as little of this as possible
Pros
• Small, reusable, readable, generic classes
• Only the variables are managed in a specific application
• The footprint between a specific app and your generic
  codebase is as small as possible - only instantiation calls
Pros
• Small, reusable, readable, generic classes
• Only the variables are managed in a specific application
• The footprint between a specific app and your generic
  codebase is as small as possible - only instantiation calls



                      & Cons
• Requires a bit more skill.
• Can often mean more bytes of code in the short term.
• Test driven development is a must.
I use MooTools
I use MooTools
• MooTools makes JavaScript easier (as do
 all frameworks).
I use MooTools
• MooTools makes JavaScript easier (as do
 all frameworks).

• It encourages you to reuse your work, and
 to write your code to be flexible for future
 use.
I use MooTools
• MooTools makes JavaScript easier (as do
 all frameworks).

• It encourages you to reuse your work, and
 to write your code to be flexible for future
 use.

• It is designed to be extended.
I use MooTools
• MooTools makes JavaScript easier (as do
 all frameworks).

• It encourages you to reuse your work, and
 to write your code to be flexible for future
 use.

• It is designed to be extended.
• These are qualities of JavaScript really;
 MooTools just makes the interface more
 accessible.

Weitere ähnliche Inhalte

Was ist angesagt?

1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basicsfuturespective
 
обзор Python
обзор Pythonобзор Python
обзор PythonYehor Nazarkin
 
About java
About javaAbout java
About javaJay Xu
 
かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版Yutaka Kato
 
Scala in practice
Scala in practiceScala in practice
Scala in practiceandyrobinson8
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscexjeffz
 
Kotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasureKotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasureDmytro Zaitsev
 
Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers輝 子安
 
SWDC 2010: Programming to Patterns
SWDC 2010: Programming to PatternsSWDC 2010: Programming to Patterns
SWDC 2010: Programming to Patternsdylanks
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To ScalaInnar Made
 

Was ist angesagt? (15)

1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
обзор Python
обзор Pythonобзор Python
обзор Python
 
About java
About javaAbout java
About java
 
かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
JavaYDL11
JavaYDL11JavaYDL11
JavaYDL11
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
 
Scala for Jedi
Scala for JediScala for Jedi
Scala for Jedi
 
Kotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasureKotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasure
 
Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers
 
JavaYDL6
JavaYDL6JavaYDL6
JavaYDL6
 
SWDC 2010: Programming to Patterns
SWDC 2010: Programming to PatternsSWDC 2010: Programming to Patterns
SWDC 2010: Programming to Patterns
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 

Ähnlich wie How to write maintainable JavaScript using classes and patterns

Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practicesManav Gupta
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_onefuturespective
 
Shibuya.js Lightning Talks
Shibuya.js Lightning TalksShibuya.js Lightning Talks
Shibuya.js Lightning Talksjeresig
 
FITC CoffeeScript 101
FITC CoffeeScript 101FITC CoffeeScript 101
FITC CoffeeScript 101Faisal Abid
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScriptNone
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 DevsJason Hanson
 
Having a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfHaving a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfNicholasflqStewartl
 
Hello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdfHello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdfirshadkumar3
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlinintelliyole
 
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxsrcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxwhitneyleman54422
 
Unit testing with PHPUnit
Unit testing with PHPUnitUnit testing with PHPUnit
Unit testing with PHPUnitferca_sl
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodecamp Romania
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.pptJyothiAmpally
 
JavaScript Classes and Inheritance
JavaScript Classes and InheritanceJavaScript Classes and Inheritance
JavaScript Classes and Inheritancemarcheiligers
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardKelsey Gilmore-Innis
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptMiao Siyu
 
javascript prototype
javascript prototypejavascript prototype
javascript prototypeHika Maeng
 

Ähnlich wie How to write maintainable JavaScript using classes and patterns (20)

Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_one
 
Shibuya.js Lightning Talks
Shibuya.js Lightning TalksShibuya.js Lightning Talks
Shibuya.js Lightning Talks
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 
FITC CoffeeScript 101
FITC CoffeeScript 101FITC CoffeeScript 101
FITC CoffeeScript 101
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 Devs
 
Having a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfHaving a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdf
 
Hello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdfHello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdf
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxsrcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
 
Lecture33
Lecture33Lecture33
Lecture33
 
Scala
ScalaScala
Scala
 
Unit testing with PHPUnit
Unit testing with PHPUnitUnit testing with PHPUnit
Unit testing with PHPUnit
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
JavaScript Classes and Inheritance
JavaScript Classes and InheritanceJavaScript Classes and Inheritance
JavaScript Classes and Inheritance
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
javascript prototype
javascript prototypejavascript prototype
javascript prototype
 

KĂźrzlich hochgeladen

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
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 

KĂźrzlich hochgeladen (20)

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...
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

How to write maintainable JavaScript using classes and patterns

  • 1. Programming To Patterns
  • 2. How I used to write
  • 3. How I used to write Classes DatePicker FormValidator Fx Request Slideshow etc...
  • 4. How I used to write var myApp = { init: function(){ myApp.apples() Classes myApp.orange() DatePicker myApp.lemons() FormValidator }, Fx apples: function(){ Request $$(‘div.apple’).each(function(apple) { Slideshow var form = apple.getElement(‘form’); etc... form.addEvent(‘submit’, funciton(event){ ....}); }); }, orange: function(){ $(‘orange’).getElements(‘li’).each... }, etc...
  • 5. How I used to write var myApp = { init: function(){ myApp.apples() Classes myApp.orange() DatePicker myApp.lemons() FormValidator }, Fx apples: function(){ Request $$(‘div.apple’).each(function(apple) { Slideshow var form = apple.getElement(‘form’); etc... form.addEvent(‘submit’, funciton(event){ ....}); }); }, orange: function(){ $(‘orange’).getElements(‘li’).each... }, etc... This tends to get out of hand
  • 6. Banging it out... <script> window.addEvent(‘domready’, function(){ $(‘myForm’).addEvent(‘submit’, function(evt){ evt.preventDefault(); this.send({ onComplete: function(result){ ... }, update: $(‘myContainer’) }); }); }); </script> This is very tempting.
  • 7. Pros • Writing the logic for a specic app is fast and furious • The test environment is the app
  • 8. Pros • Writing the logic for a specic app is fast and furious • The test environment is the app & Cons • It’s much harder to maintain • A high percentage of code you write for the app isn’t reusable
  • 10. Using Classes This is how MooTools does it var Human = new Class({ isAlive: true, energy: 1, eat: function(){ this.energy++; } }); Human
  • 11. Using Classes This is how MooTools does it var Human = new Class({ isAlive: true, energy: 1, eat: function(){ this.energy++; } }); var bob = new Human(); //bob.energy === 1 bob.eat(); //bob.energy === 2 Human bob
  • 13. Extending Classes var Human = new Class({ initialize: function(name, age){ this.name = name; this.age = age; }, isAlive: true, energy: 1, eat: function(){ this.energy++; } });
  • 14. Extending Classes var Human = new Class({ var Ninja = new Class({ initialize: function(name, age){ Extends: Human, this.name = name; initialize: function(side, name, age){ this.age = age; this.side = side; }, this.parent(name, age); isAlive: true, }, energy: 1, energy: 100, eat: function(){ attack: function(target){ this.energy++; this.energy = this.energy - 5; } target.isAlive = false; }); } });
  • 15. Extending Classes var Human = new Class({ var Ninja = new Class({ initialize: function(name, age){ Extends: Human, this.name = name; initialize: function(side, name, age){ this.age = age; this.side = side; }, this.parent(name, age); isAlive: true, }, energy: 1, energy: 100, eat: function(){ attack: function(target){ this.energy++; this.energy = this.energy - 5; } target.isAlive = false; }); } });
  • 16. Extending Classes var Human = new Class({ var Ninja = new Class({ initialize: function(name, age){ Extends: Human, this.name = name; initialize: function(side, name, age){ this.age = age; this.side = side; }, this.parent(name, age); isAlive: true, }, energy: 1, energy: 100, eat: function(){ attack: function(target){ this.energy++; this.energy = this.energy - 5; } target.isAlive = false; }); } }); var bob = new Human('Bob', 25);
  • 17. Extending Classes var Human = new Class({ var Ninja = new Class({ initialize: function(name, age){ Extends: Human, this.name = name; initialize: function(side, name, age){ this.age = age; this.side = side; }, this.parent(name, age); isAlive: true, }, energy: 1, energy: 100, eat: function(){ attack: function(target){ this.energy++; this.energy = this.energy - 5; } target.isAlive = false; }); } }); var bob = new Human('Bob', 25); var blackNinja = new Ninja('evil', 'Nin Tendo', 'unknown'); //blackNinja.isAlive = true //blackNinja.name = 'Nin Tendo' blackNinja.attack(bob); //bob never had a chance
  • 19. Implementing Classes var Human = new Class({ initialize: function(name, age){ this.name = name; this.age = age; }, isAlive: true, energy: 1, eat: function(){ this.energy++; } });
  • 20. Implementing Classes var Human = new Class({ initialize: function(name, age){ this.name = name; this.age = age; }, isAlive: true, energy: 1, eat: function(){ this.energy++; } }); var Warrior = new Class({ energy: 100, kills: 0, attack: function(target){ if (target.energy < this.energy) { target.isAlive = false; this.kills++; } this.energy = this.energy - 5; } });
  • 21. Implementing Classes var Human = new Class({ var Ninja = new Class({ initialize: function(name, age){ Extends: Human, this.name = name; Implements: [Warrior], this.age = age; initialize: function(side, name, age){ }, this.side = side; isAlive: true, this.parent(name, age); energy: 1, } eat: function(){ }); this.energy++; } }); var Warrior = new Class({ var Samurai = new Class({ energy: 100, Extends: Human, kills: 0, Implements: [Warrior], attack: function(target){ side: 'good', if (target.energy < this.energy) { energy: 1000 target.isAlive = false; }); this.kills++; } this.energy = this.energy - 5; } });
  • 22. When to write a class...
  • 23. When to write a class...
  • 24. When to write a class...
  • 25. When to write a class...
  • 26. When to write a class...
  • 27. Key Aspects of JS Classes
  • 28. Key Aspects of JS Classes • Shallow inheritance works best.
  • 29. Key Aspects of JS Classes • Shallow inheritance works best. • Break up logic into small methods.
  • 30. Key Aspects of JS Classes • Shallow inheritance works best. • Break up logic into small methods. • Break up functionality into small classes.
  • 31. Key Aspects of JS Classes • Shallow inheritance works best. • Break up logic into small methods. • Break up functionality into small classes. • Build ‘controller’ classes for grouped functionality.
  • 32. Key Aspects of JS Classes • Shallow inheritance works best. • Break up logic into small methods. • Break up functionality into small classes. • Build ‘controller’ classes for grouped functionality. • Use options and events liberally.
  • 33. Key Aspects of JS Classes • Shallow inheritance works best. • Break up logic into small methods. • Break up functionality into small classes. • Build ‘controller’ classes for grouped functionality. • Use options and events liberally. • Don’t be afraid to refactor, but avoid breaking the interface.
  • 34. Let’s look at that earlier example again ... <script> $(‘myForm’).addEvent(‘submit’, function(evt){ evt.preventDefault(); this.send({ onComplete: function(result){ ... }, update: $(‘myContainer’) }); }); </script>
  • 35. Program a Pattern var FormUpdater = new Class({ initialize: function(form, container, options) { this.form = $(form); this.container = $(container); this.request = new Request(options); this.attach(); }, attach: function(){ this.form.addEvent(‘submit’, this.send.bind(this)); }, send: function(evt){ if (evt) evt.preventDefault(); this.request.send({ url: this.form.get(‘action’), onComplete: this.onComplete.bind(this) }); }, onComplete: function(responseTxt){ this.container.set(‘html’, responseTxt); } }); new FormUpdater($(‘myForm’), $(‘myContainer’));
  • 36. ...and then extend it var FormUpdater.Append = new Class({ Extends: FormUpdater, onComplete: function(responseTxt){ this.container.adopt( new Element(‘div’, {html: responseTxt}) ); } }); new FormUpdater.Append($(‘myForm’), $(‘myTarget’));
  • 37. How I write now
  • 38. How I write now var myApp = { init: function(){ myApp.apples() Classes myApp.orange() DatePicker myApp.lemons() FormValidator }, Fx apples: function(){ Request new AppleGroup($$(‘div.apple’)); Slideshow }, Apple orange: function(){ AppleGroup new Orange($(‘orange’) Orange }, etc... etc...
  • 39. How I write now var myApp = { init: function(){ myApp.apples() Classes myApp.orange() DatePicker myApp.lemons() FormValidator }, Fx apples: function(){ Request new AppleGroup($$(‘div.apple’)); Slideshow }, Apple orange: function(){ AppleGroup new Orange($(‘orange’) Orange }, etc... etc... I write as little of this as possible
  • 40. Pros • Small, reusable, readable, generic classes • Only the variables are managed in a specic application • The footprint between a specic app and your generic codebase is as small as possible - only instantiation calls
  • 41. Pros • Small, reusable, readable, generic classes • Only the variables are managed in a specic application • The footprint between a specic app and your generic codebase is as small as possible - only instantiation calls & Cons • Requires a bit more skill. • Can often mean more bytes of code in the short term. • Test driven development is a must.
  • 43. I use MooTools • MooTools makes JavaScript easier (as do all frameworks).
  • 44. I use MooTools • MooTools makes JavaScript easier (as do all frameworks). • It encourages you to reuse your work, and to write your code to be flexible for future use.
  • 45. I use MooTools • MooTools makes JavaScript easier (as do all frameworks). • It encourages you to reuse your work, and to write your code to be flexible for future use. • It is designed to be extended.
  • 46. I use MooTools • MooTools makes JavaScript easier (as do all frameworks). • It encourages you to reuse your work, and to write your code to be flexible for future use. • It is designed to be extended. • These are qualities of JavaScript really; MooTools just makes the interface more accessible.