SlideShare una empresa de Scribd logo
1 de 46
Descargar para leer sin conexión
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.

Más contenido relacionado

La actualidad más candente

About java
About javaAbout java
About java
Jay Xu
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
jeffz
 

La actualidad más candente (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
 

Similar a Programming To Patterns

Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
Manav Gupta
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_one
futurespective
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
Sagie Davidovich
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
None
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 Devs
Jason 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.pdf
NicholasflqStewartl
 
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
irshadkumar3
 
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxsrcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
whitneyleman54422
 
Unit testing with PHPUnit
Unit testing with PHPUnitUnit testing with PHPUnit
Unit testing with PHPUnit
ferca_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 Groovy
Codecamp Romania
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
Miao Siyu
 

Similar a Programming To 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
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
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
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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...
 
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
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 

Programming To 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 specific app is fast and furious • The test environment is the app
  • 8. 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
  • 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 specific application • The footprint between a specific 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 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.
  • 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.