SlideShare une entreprise Scribd logo
1  sur  46
Télécharger pour lire hors ligne
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.

Contenu connexe

Tendances

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

Tendances (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
 

Similaire à 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
 

Similaire à 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
 

Dernier

Dernier (20)

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
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...
 
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?
 
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
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

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.