SlideShare ist ein Scribd-Unternehmen logo
1 von 89
Downloaden Sie, um offline zu lesen
Clean JavaScript


http://www.ïŹ‚ickr.com/photos/hoshikowolrd/5151171470/




                                                         Sapporo.js
SaCSS vol.29 - 2011.11.26                              (Ryunosuke SATO)
Community for people who like JavaScript.




      Sapporo.js
Sapporo.js




http://sapporojs.org
Sapporo.js




Now learning
I’m a programmer
@tricknotes
Clean JavaScript


http://www.ïŹ‚ickr.com/photos/hoshikowolrd/5151171470/




                                                         Sapporo.js
SaCSS vol.29 - 2011.11.26                              (Ryunosuke SATO)
JavaScript
JavaScript
about JavaScript
Works in everywhere!
http://www.ïŹ‚ickr.com/photos/peco-sunnyday/2752403413/




                interesting!
I like
JavaScript is most popular!
but...
http://www.ïŹ‚ickr.com/photos/maynard/6105929170/




                              difïŹcult
Now training...
?
                     ?
How to face the difïŹculty
Oops... :(
some ideas
with

DOM
point
HTML   JavaScript
HTML   JavaScript
here!




HTML       JavaScript
practice
- Attach events from outer -

problem


   JavaScript
- Attach events from outer -

solution


HTML
 JavaScript
- Attach events from outer -




<a onclick=”showMessage()”>Click me</a>




                                    code smell
- Attach events from outer -




<a id=”showMessage”>Click me</a>


var a = document.getElementById(‘showMessage’);
a.addEventListener(‘click’, showMessage);



                                       improvement
- Separate from Selector -

problem


HTML   id   class
- Separate from Selector -

solution



HTML   id   class
- Separate from Selector -




function showPhoto(photoId) {
  var photo = document.getElementById(‘photo-’ + photoId);
  // do ...
}
- Separate from Selector -




function showPhoto(photoId) {
  var photo = document.getElementById(‘photo-’ + photoId);
  // do ...
}




                                              code smell
- Separate from Selector -


var showPhoto = function(element) {
  // do ...
}

var photo = document.getElementById(‘photo-12’);
showPhoto(photo);




                                      improvement
- modulized functions -

problem
- modulized functions -

solution
- modulized functions -

// users.js
var showUserName = function() {
  // do somethig
}

var showUserAge = function(){
  // do somethig
}

var validateUserForm = function() {
  // do somethig
}                                   code smell
- modulized functions -

// users.js
var showUserName = function() {
  // do somethig
}                             global

var showUserAge = function(){
  // do somethig
}

var validateUserForm = function() {
  // do somethig
}
- modulized functions -
// users.js
var users = {};
                               global
users.showName = function () {
  // do somethig
}

users.showAge = function (){
  // do somethig
}

users.validateForm = function () {
  // do somethig
}
- modulized functions -
// users.js
(function(global) {
  global.users = {};            global

 users.showName = function () {
   // do somethig
 }

  // ...
)(this);


                                    improvement
overwrite behavior -

problem


     JavaScript
 DOM
overwrite behavior -
solution


 DOM
           DOM
overwrite behavior -

// using jQuery

$(‘a#showDialog’).click(function() {
  $.ajax(‘/about’, {
    success: function(html) {
      // do something...
    }
  });
});




                                       code smell
overwrite behavior -

// using jQuery

$(‘a#showDialog’).click(function() {
  $.ajax($(this).attr(‘href’), {
    success: function(html) {
      // do something...
    }
  });
});




                                   improvement
shallow scope -

problem
shallow scope -

solution


        2            function


    →         this
shallow scope -


// using jQuery

var $elements = $(‘a#remote’);
$elements.click(function() {
  var url = $(this).attr(‘href’);
  $.ajax(url, {
    success: function(html) {
      var text = $(html).text();
      $element.text(text);
    }
  });
  return false;
});
shallow scope -


// using jQuery

var $elements = $(‘a#remote’);
$elements.click(function() {         deep
  var url = $(this).attr(‘href’);
  $.ajax(url, {
    success: function(html) {
      var text = $(html).text();
      $element.text(text);
    }
  });
  return false;
});

                                            code smell
shallow scope -


// using jQuery

var $elements = $(‘a#remote’);
$elements.click(function() {
  var url = $(this).attr(‘href’);
  $.ajax(url, {
    success: function(html) {
       var text = $(html).text();
       $(this).text(text);
    },
    context: this
  });
  return false;
});
                                           improvement
DOM       - DOM to model -

problem


DOM
DOM        - DOM to model -

solution


DOM
DOM                                     - DOM to model -


var element = document.getElementById(‘message’);
element.addEventListener(‘click’, function() {
  // this == element
  if (this.getAttribute(‘data-is-checked’)) {
    this.setAttribute(‘data-is-checked’, true);
    this.innerText = ‘clicked!’;
  }
});




                                                code smell
DOM                                                        - DOM to model -


var domToModel = function(element, Model) {
  var method, name, object, parent, proto;
  model = Object.create(element);
  proto = Model.prototype;
  for (name in proto) {
    method = proto[name];
    model[name] = method;
  }
  Model.apply(model);
  return model;
};

var CustomElement = function() {};
CustomElement.prototype.showText = function() {
   if (!this.getAttribute(‘data-is-checked’)) {   var element = document.getElementById(‘message’);
    this.setAttribute(‘data-is-checked’, true);   var model = domToModel(element, CustomElement);
    this.innerText = ‘clicked!’;                  model.addEventListener(‘click’, function() {
  }                                                 model.showText();
};                                                });
DOM                                                        - DOM to model -


var domToModel = function(element, Model) {
  var method, name, object, parent, proto;
  model = Object.create(element);
  proto = Model.prototype;
  for (name in proto) {
    method = proto[name];
    model[name] = method;
  }
  Model.apply(model);
  return model;
};

var CustomElement = function() {};
CustomElement.prototype.showText = function() {
   if (!this.getAttribute(‘data-is-checked’)) {   var element = document.getElementById(‘message’);
    this.setAttribute(‘data-is-checked’, true);   var model = domToModel(element, CustomElement);
    this.innerText = ‘clicked!’;                  model.addEventListener(‘click’, function() {
  }                                                 model.showText();
};                                                });
DOM                                                        - DOM to model -


var domToModel = function(element, Model) {
  var method, name, object, parent, proto;
  model = Object.create(element);
  proto = Model.prototype;
  for (name in proto) {
    method = proto[name];
    model[name] = method;
  }
  Model.apply(model);
  return model;
};

var CustomElement = function() {};
CustomElement.prototype.showText = function() {
   if (!this.getAttribute(‘data-is-checked’)) {   var element = document.getElementById(‘message’);
    this.setAttribute(‘data-is-checked’, true);   var model = domToModel(element, CustomElement);
    this.innerText = ‘clicked!’;                  model.addEventListener(‘click’, function() {
  }                                                 model.showText();
};                                                });

                                                                   improvement
- separate logic with view -

problem
- separate logic with view -
solution
- separate logic with view -

function createTimer() {
  var timerId;
  var startTimer = function(millisec) {
    timerId = setTimeout(function() {
      $(‘.timeout’).text(â€˜ïŹnished’);
    }, millisec);
  }
  var stopTimer = function() {
    clearTimeout(timerId);
  }
  return {
    startTimer: startTimer,
    stopTimer: stopTimer
  }
}
- separate logic with view -

function createTimer() {
  var timerId;
  var startTimer = function(millisec) {
    timerId = setTimeout(function() {
      $(‘.timeout’).text(â€˜ïŹnished’);      view
    }, millisec);
  }
  var stopTimer = function() {
    clearTimeout(timerId);
  }
  return {
    startTimer: startTimer,
    stopTimer: stopTimer
  }
}
                                                   code smell
- separate logic with view -
function Timer(millisec) {
  this. millisec = millisec;
  this.callbacks = [];
  this.timerId = null;
}

Timer.prototype.afterFinish = function(callback) {
  return this.callbacks.push(callback);
};

Timer.prototype.start = function() {
  var callbacks = this.callbacks;
  this.timerId = setTimeout(function() {
    var callback, i, length;
    for (i = 0, length = callbacks.length; i < length; i++) {   var timer = new Timer(1000);
      callback = callbacks[i];                                  timer.afterFinish(function() {
      callback();                                                 $('.timer .message').text('Finished!!');
    }                                                           });
  }, this. millisec);                                           timer.start();
};

Timer.prototype.stop = function() {
  clearTimeout(this.timerId);
}
- separate logic with view -
function Timer(millisec) {
  this. millisec = millisec;
  this.callbacks = [];

}
  this.timerId = null;
                                                                  model
Timer.prototype.afterFinish = function(callback) {
  return this.callbacks.push(callback);
};

Timer.prototype.start = function() {                                      view
  var callbacks = this.callbacks;
  this.timerId = setTimeout(function() {
    var callback, i, length;
    for (i = 0, length = callbacks.length; i < length; i++) {   var timer = new Timer(1000);
      callback = callbacks[i];                                  timer.afterFinish(function() {
      callback();                                                 $('.timer .message').text('Finished!!');
    }                                                           });
  }, this. millisec);                                           timer.start();
};

Timer.prototype.stop = function() {
  clearTimeout(this.timerId);
}                                                                      improvement
A tiny fraction
others...
Pure JavaScript
Application
https://gist.github.com/1362110
http://documentcloud.github.com/backbone/
http://www.sproutcore.com/
interest




http://www.ïŹ‚ickr.com/photos/bonguri/4610536789/
reading
Good text
writing
Shall we learn
      about
Clean JavaScript?

Weitere Àhnliche Inhalte

Was ist angesagt?

Backbone.js
Backbone.jsBackbone.js
Backbone.jsOmnia Helmi
 
Integrating Angular js & three.js
Integrating Angular js & three.jsIntegrating Angular js & three.js
Integrating Angular js & three.jsJosh Staples
 
Developing large scale JavaScript applications
Developing large scale JavaScript applicationsDeveloping large scale JavaScript applications
Developing large scale JavaScript applicationsMilan Korsos
 
Javascript MVVM with Vue.JS
Javascript MVVM with Vue.JSJavascript MVVM with Vue.JS
Javascript MVVM with Vue.JSEueung Mulyana
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widgetTudor Barbu
 
jQuery Internals + Cool Stuff
jQuery Internals + Cool StuffjQuery Internals + Cool Stuff
jQuery Internals + Cool Stuffjeresig
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS IntroductionDavid Ličen
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overviewjeresig
 
MVC pattern for widgets
MVC pattern for widgetsMVC pattern for widgets
MVC pattern for widgetsBehnam Taraghi
 
Client Side MVC & Angular
Client Side MVC & AngularClient Side MVC & Angular
Client Side MVC & AngularAlexe Bogdan
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJsTudor Barbu
 
Vue.js + Django - configuraciĂłn para desarrollo con webpack y HMR
Vue.js + Django - configuraciĂłn para desarrollo con webpack y HMRVue.js + Django - configuraciĂłn para desarrollo con webpack y HMR
Vue.js + Django - configuraciĂłn para desarrollo con webpack y HMRJavier AbadĂ­a
 
Vue js ć€§ćž‹ć°ˆæĄˆæž¶æ§‹
Vue js ć€§ćž‹ć°ˆæĄˆæž¶æ§‹Vue js ć€§ćž‹ć°ˆæĄˆæž¶æ§‹
Vue js ć€§ćž‹ć°ˆæĄˆæž¶æ§‹Hina Chen
 
AngularJS - Overcoming performance issues. Limits.
AngularJS - Overcoming performance issues. Limits.AngularJS - Overcoming performance issues. Limits.
AngularJS - Overcoming performance issues. Limits.Dragos Mihai Rusu
 
The Many Ways to Build Modular JavaScript
The Many Ways to Build Modular JavaScriptThe Many Ways to Build Modular JavaScript
The Many Ways to Build Modular JavaScriptTim Perry
 
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...Christian Janz
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.jsJavier Lafora Rey
 
Basic Tutorial of React for Programmers
Basic Tutorial of React for ProgrammersBasic Tutorial of React for Programmers
Basic Tutorial of React for ProgrammersDavid Rodenas
 

Was ist angesagt? (20)

Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Integrating Angular js & three.js
Integrating Angular js & three.jsIntegrating Angular js & three.js
Integrating Angular js & three.js
 
Developing large scale JavaScript applications
Developing large scale JavaScript applicationsDeveloping large scale JavaScript applications
Developing large scale JavaScript applications
 
Javascript MVVM with Vue.JS
Javascript MVVM with Vue.JSJavascript MVVM with Vue.JS
Javascript MVVM with Vue.JS
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widget
 
jQuery Internals + Cool Stuff
jQuery Internals + Cool StuffjQuery Internals + Cool Stuff
jQuery Internals + Cool Stuff
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
 
MVC pattern for widgets
MVC pattern for widgetsMVC pattern for widgets
MVC pattern for widgets
 
Client Side MVC & Angular
Client Side MVC & AngularClient Side MVC & Angular
Client Side MVC & Angular
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
 
Vue.js + Django - configuraciĂłn para desarrollo con webpack y HMR
Vue.js + Django - configuraciĂłn para desarrollo con webpack y HMRVue.js + Django - configuraciĂłn para desarrollo con webpack y HMR
Vue.js + Django - configuraciĂłn para desarrollo con webpack y HMR
 
Vue js ć€§ćž‹ć°ˆæĄˆæž¶æ§‹
Vue js ć€§ćž‹ć°ˆæĄˆæž¶æ§‹Vue js ć€§ćž‹ć°ˆæĄˆæž¶æ§‹
Vue js ć€§ćž‹ć°ˆæĄˆæž¶æ§‹
 
AngularJS - Overcoming performance issues. Limits.
AngularJS - Overcoming performance issues. Limits.AngularJS - Overcoming performance issues. Limits.
AngularJS - Overcoming performance issues. Limits.
 
The Many Ways to Build Modular JavaScript
The Many Ways to Build Modular JavaScriptThe Many Ways to Build Modular JavaScript
The Many Ways to Build Modular JavaScript
 
Js unit testing
Js unit testingJs unit testing
Js unit testing
 
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Test slideshare document
Test slideshare documentTest slideshare document
Test slideshare document
 
Basic Tutorial of React for Programmers
Basic Tutorial of React for ProgrammersBasic Tutorial of React for Programmers
Basic Tutorial of React for Programmers
 

Ähnlich wie Clean Javascript

Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery ApplicationsRebecca Murphey
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
Backbone Basics with Examples
Backbone Basics with ExamplesBackbone Basics with Examples
Backbone Basics with ExamplesSergey Bolshchikov
 
Getting the Most Out of jQuery Widgets
Getting the Most Out of jQuery WidgetsGetting the Most Out of jQuery Widgets
Getting the Most Out of jQuery Widgetsvelveeta_512
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secretsBastian Feder
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
Building Robust jQuery Plugins
Building Robust jQuery PluginsBuilding Robust jQuery Plugins
Building Robust jQuery PluginsJörn Zaefferer
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Christoffer Noring
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsJarod Ferguson
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secretsBastian Feder
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
Building complex User Interfaces with Sitecore and React
Building complex User Interfaces with Sitecore and ReactBuilding complex User Interfaces with Sitecore and React
Building complex User Interfaces with Sitecore and ReactJonne Kats
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
Unittests fĂŒr Dummies
Unittests fĂŒr DummiesUnittests fĂŒr Dummies
Unittests fĂŒr DummiesLars Jankowfsky
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
 

Ähnlich wie Clean Javascript (20)

Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Backbone Basics with Examples
Backbone Basics with ExamplesBackbone Basics with Examples
Backbone Basics with Examples
 
Getting the Most Out of jQuery Widgets
Getting the Most Out of jQuery WidgetsGetting the Most Out of jQuery Widgets
Getting the Most Out of jQuery Widgets
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
Building Robust jQuery Plugins
Building Robust jQuery PluginsBuilding Robust jQuery Plugins
Building Robust jQuery Plugins
 
BVJS
BVJSBVJS
BVJS
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Building complex User Interfaces with Sitecore and React
Building complex User Interfaces with Sitecore and ReactBuilding complex User Interfaces with Sitecore and React
Building complex User Interfaces with Sitecore and React
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
jQuery
jQueryjQuery
jQuery
 
Unittests fĂŒr Dummies
Unittests fĂŒr DummiesUnittests fĂŒr Dummies
Unittests fĂŒr Dummies
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 

Mehr von Ryunosuke SATO

片手間JS on Rails
片手間JS on Rails片手間JS on Rails
片手間JS on RailsRyunosuke SATO
 
Ember ă‚łăƒŸăƒ„ăƒ‹ăƒ†ă‚Łăšă‚ăŸă—
Ember ă‚łăƒŸăƒ„ăƒ‹ăƒ†ă‚Łăšă‚ăŸă—Ember ă‚łăƒŸăƒ„ăƒ‹ăƒ†ă‚Łăšă‚ăŸă—
Ember ă‚łăƒŸăƒ„ăƒ‹ăƒ†ă‚Łăšă‚ăŸă—Ryunosuke SATO
 
gem ăźæŽąă—æ–č
gem ăźæŽąă—æ–čgem ăźæŽąă—æ–č
gem ăźæŽąă—æ–čRyunosuke SATO
 
Rails あるある
Rails あるあるRails あるある
Rails あるあるRyunosuke SATO
 
Node.js ă‚’éžă¶ăšă 遞ばăȘいべき
Node.js ă‚’éžă¶ăšă 遞ばăȘいべきNode.js ă‚’éžă¶ăšă 遞ばăȘいべき
Node.js ă‚’éžă¶ăšă 遞ばăȘいべきRyunosuke SATO
 
もっべはじめる Ember.js !! ~ Getting started with Ember.js more ~
もっべはじめる Ember.js !! ~ Getting started with Ember.js more ~もっべはじめる Ember.js !! ~ Getting started with Ember.js more ~
もっべはじめる Ember.js !! ~ Getting started with Ember.js more ~Ryunosuke SATO
 
はじめる Ember.js ~ Getting started with ember.js ~
はじめる Ember.js ~ Getting started with ember.js ~はじめる Ember.js ~ Getting started with ember.js ~
はじめる Ember.js ~ Getting started with ember.js ~Ryunosuke SATO
 
How to relaunch "sapporojs.org" ~Introduction to middleman~
How to relaunch "sapporojs.org" ~Introduction to middleman~How to relaunch "sapporojs.org" ~Introduction to middleman~
How to relaunch "sapporojs.org" ~Introduction to middleman~Ryunosuke SATO
 
Introduction for Browser Side MVC
Introduction for Browser Side MVCIntroduction for Browser Side MVC
Introduction for Browser Side MVCRyunosuke SATO
 
ă‚łăƒŸăƒ„ăƒ‹ăƒ†ă‚Łăźă‚ă‚‹éąšæ™Ż
ă‚łăƒŸăƒ„ăƒ‹ăƒ†ă‚Łăźă‚ă‚‹éąšæ™Żă‚łăƒŸăƒ„ăƒ‹ăƒ†ă‚Łăźă‚ă‚‹éąšæ™Ż
ă‚łăƒŸăƒ„ăƒ‹ăƒ†ă‚Łăźă‚ă‚‹éąšæ™ŻRyunosuke SATO
 
capybara で濫適ăȘテă‚čăƒˆç”ŸæŽ»ă‚’
capybara で濫適ăȘテă‚čăƒˆç”ŸæŽ»ă‚’capybara で濫適ăȘテă‚čăƒˆç”ŸæŽ»ă‚’
capybara で濫適ăȘテă‚čăƒˆç”ŸæŽ»ă‚’Ryunosuke SATO
 
Social coding ă‚’ă‚‚ăŁăšæ„œă—ăżăŸă„ă‚ăȘたま
Social coding ă‚’ă‚‚ăŁăšæ„œă—ăżăŸă„ă‚ăȘたまSocial coding ă‚’ă‚‚ăŁăšæ„œă—ăżăŸă„ă‚ăȘたま
Social coding ă‚’ă‚‚ăŁăšæ„œă—ăżăŸă„ă‚ăȘたまRyunosuke SATO
 
Node.jsっおどうăȘăźïŒŸ
Node.jsっおどうăȘăźïŒŸNode.jsっおどうăȘăźïŒŸ
Node.jsっおどうăȘăźïŒŸRyunosuke SATO
 
ă‚ąă‚žăƒŁă‚€ăƒ«çš„ă‚ąăƒ—ăƒ­ăƒŒăƒă‹ă‚‰èŠ‹ăˆăŠăăŸă“ăš
ă‚ąă‚žăƒŁă‚€ăƒ«çš„ă‚ąăƒ—ăƒ­ăƒŒăƒă‹ă‚‰èŠ‹ăˆăŠăăŸă“ăšă‚ąă‚žăƒŁă‚€ăƒ«çš„ă‚ąăƒ—ăƒ­ăƒŒăƒă‹ă‚‰èŠ‹ăˆăŠăăŸă“ăš
ă‚ąă‚žăƒŁă‚€ăƒ«çš„ă‚ąăƒ—ăƒ­ăƒŒăƒă‹ă‚‰èŠ‹ăˆăŠăăŸă“ăšRyunosuke SATO
 
è„±ăƒŹă‚Źă‚·ăƒŒćŒ–èšˆç”»
è„±ăƒŹă‚Źă‚·ăƒŒćŒ–èšˆç”»è„±ăƒŹă‚Źă‚·ăƒŒćŒ–èšˆç”»
è„±ăƒŹă‚Źă‚·ăƒŒćŒ–èšˆç”»Ryunosuke SATO
 
Pusherずcanvasă§äœœă‚‹ăƒȘă‚ąăƒ«ă‚żă‚€ăƒ ă‚°ăƒ©ăƒ•
Pusherずcanvasă§äœœă‚‹ăƒȘă‚ąăƒ«ă‚żă‚€ăƒ ă‚°ăƒ©ăƒ•Pusherずcanvasă§äœœă‚‹ăƒȘă‚ąăƒ«ă‚żă‚€ăƒ ă‚°ăƒ©ăƒ•
Pusherずcanvasă§äœœă‚‹ăƒȘă‚ąăƒ«ă‚żă‚€ăƒ ă‚°ăƒ©ăƒ•Ryunosuke SATO
 
ServerSideJavaScript
ServerSideJavaScriptServerSideJavaScript
ServerSideJavaScriptRyunosuke SATO
 

Mehr von Ryunosuke SATO (17)

片手間JS on Rails
片手間JS on Rails片手間JS on Rails
片手間JS on Rails
 
Ember ă‚łăƒŸăƒ„ăƒ‹ăƒ†ă‚Łăšă‚ăŸă—
Ember ă‚łăƒŸăƒ„ăƒ‹ăƒ†ă‚Łăšă‚ăŸă—Ember ă‚łăƒŸăƒ„ăƒ‹ăƒ†ă‚Łăšă‚ăŸă—
Ember ă‚łăƒŸăƒ„ăƒ‹ăƒ†ă‚Łăšă‚ăŸă—
 
gem ăźæŽąă—æ–č
gem ăźæŽąă—æ–čgem ăźæŽąă—æ–č
gem ăźæŽąă—æ–č
 
Rails あるある
Rails あるあるRails あるある
Rails あるある
 
Node.js ă‚’éžă¶ăšă 遞ばăȘいべき
Node.js ă‚’éžă¶ăšă 遞ばăȘいべきNode.js ă‚’éžă¶ăšă 遞ばăȘいべき
Node.js ă‚’éžă¶ăšă 遞ばăȘいべき
 
もっべはじめる Ember.js !! ~ Getting started with Ember.js more ~
もっべはじめる Ember.js !! ~ Getting started with Ember.js more ~もっべはじめる Ember.js !! ~ Getting started with Ember.js more ~
もっべはじめる Ember.js !! ~ Getting started with Ember.js more ~
 
はじめる Ember.js ~ Getting started with ember.js ~
はじめる Ember.js ~ Getting started with ember.js ~はじめる Ember.js ~ Getting started with ember.js ~
はじめる Ember.js ~ Getting started with ember.js ~
 
How to relaunch "sapporojs.org" ~Introduction to middleman~
How to relaunch "sapporojs.org" ~Introduction to middleman~How to relaunch "sapporojs.org" ~Introduction to middleman~
How to relaunch "sapporojs.org" ~Introduction to middleman~
 
Introduction for Browser Side MVC
Introduction for Browser Side MVCIntroduction for Browser Side MVC
Introduction for Browser Side MVC
 
ă‚łăƒŸăƒ„ăƒ‹ăƒ†ă‚Łăźă‚ă‚‹éąšæ™Ż
ă‚łăƒŸăƒ„ăƒ‹ăƒ†ă‚Łăźă‚ă‚‹éąšæ™Żă‚łăƒŸăƒ„ăƒ‹ăƒ†ă‚Łăźă‚ă‚‹éąšæ™Ż
ă‚łăƒŸăƒ„ăƒ‹ăƒ†ă‚Łăźă‚ă‚‹éąšæ™Ż
 
capybara で濫適ăȘテă‚čăƒˆç”ŸæŽ»ă‚’
capybara で濫適ăȘテă‚čăƒˆç”ŸæŽ»ă‚’capybara で濫適ăȘテă‚čăƒˆç”ŸæŽ»ă‚’
capybara で濫適ăȘテă‚čăƒˆç”ŸæŽ»ă‚’
 
Social coding ă‚’ă‚‚ăŁăšæ„œă—ăżăŸă„ă‚ăȘたま
Social coding ă‚’ă‚‚ăŁăšæ„œă—ăżăŸă„ă‚ăȘたまSocial coding ă‚’ă‚‚ăŁăšæ„œă—ăżăŸă„ă‚ăȘたま
Social coding ă‚’ă‚‚ăŁăšæ„œă—ăżăŸă„ă‚ăȘたま
 
Node.jsっおどうăȘăźïŒŸ
Node.jsっおどうăȘăźïŒŸNode.jsっおどうăȘăźïŒŸ
Node.jsっおどうăȘăźïŒŸ
 
ă‚ąă‚žăƒŁă‚€ăƒ«çš„ă‚ąăƒ—ăƒ­ăƒŒăƒă‹ă‚‰èŠ‹ăˆăŠăăŸă“ăš
ă‚ąă‚žăƒŁă‚€ăƒ«çš„ă‚ąăƒ—ăƒ­ăƒŒăƒă‹ă‚‰èŠ‹ăˆăŠăăŸă“ăšă‚ąă‚žăƒŁă‚€ăƒ«çš„ă‚ąăƒ—ăƒ­ăƒŒăƒă‹ă‚‰èŠ‹ăˆăŠăăŸă“ăš
ă‚ąă‚žăƒŁă‚€ăƒ«çš„ă‚ąăƒ—ăƒ­ăƒŒăƒă‹ă‚‰èŠ‹ăˆăŠăăŸă“ăš
 
è„±ăƒŹă‚Źă‚·ăƒŒćŒ–èšˆç”»
è„±ăƒŹă‚Źă‚·ăƒŒćŒ–èšˆç”»è„±ăƒŹă‚Źă‚·ăƒŒćŒ–èšˆç”»
è„±ăƒŹă‚Źă‚·ăƒŒćŒ–èšˆç”»
 
Pusherずcanvasă§äœœă‚‹ăƒȘă‚ąăƒ«ă‚żă‚€ăƒ ă‚°ăƒ©ăƒ•
Pusherずcanvasă§äœœă‚‹ăƒȘă‚ąăƒ«ă‚żă‚€ăƒ ă‚°ăƒ©ăƒ•Pusherずcanvasă§äœœă‚‹ăƒȘă‚ąăƒ«ă‚żă‚€ăƒ ă‚°ăƒ©ăƒ•
Pusherずcanvasă§äœœă‚‹ăƒȘă‚ąăƒ«ă‚żă‚€ăƒ ă‚°ăƒ©ăƒ•
 
ServerSideJavaScript
ServerSideJavaScriptServerSideJavaScript
ServerSideJavaScript
 

KĂŒrzlich hochgeladen

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...apidays
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
🐬 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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
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
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
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 WorkerThousandEyes
 
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)wesley chun
 

KĂŒrzlich hochgeladen (20)

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...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
+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...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
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
 
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
 
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?
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
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)
 

Clean Javascript

  • 1. Clean JavaScript http://www.ïŹ‚ickr.com/photos/hoshikowolrd/5151171470/ Sapporo.js SaCSS vol.29 - 2011.11.26 (Ryunosuke SATO)
  • 2. Community for people who like JavaScript. Sapporo.js
  • 5.
  • 8.
  • 9. Clean JavaScript http://www.ïŹ‚ickr.com/photos/hoshikowolrd/5151171470/ Sapporo.js SaCSS vol.29 - 2011.11.26 (Ryunosuke SATO)
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 23. JavaScript is most popular!
  • 27. ? ? How to face the difïŹculty
  • 28.
  • 29.
  • 33. point
  • 34. HTML JavaScript
  • 35. HTML JavaScript
  • 36. here! HTML JavaScript
  • 38. - Attach events from outer - problem JavaScript
  • 39. - Attach events from outer - solution HTML JavaScript
  • 40. - Attach events from outer - <a onclick=”showMessage()”>Click me</a> code smell
  • 41. - Attach events from outer - <a id=”showMessage”>Click me</a> var a = document.getElementById(‘showMessage’); a.addEventListener(‘click’, showMessage); improvement
  • 42. - Separate from Selector - problem HTML id class
  • 43. - Separate from Selector - solution HTML id class
  • 44. - Separate from Selector - function showPhoto(photoId) { var photo = document.getElementById(‘photo-’ + photoId); // do ... }
  • 45. - Separate from Selector - function showPhoto(photoId) { var photo = document.getElementById(‘photo-’ + photoId); // do ... } code smell
  • 46. - Separate from Selector - var showPhoto = function(element) { // do ... } var photo = document.getElementById(‘photo-12’); showPhoto(photo); improvement
  • 48. - modulized functions - solution
  • 49. - modulized functions - // users.js var showUserName = function() { // do somethig } var showUserAge = function(){ // do somethig } var validateUserForm = function() { // do somethig } code smell
  • 50. - modulized functions - // users.js var showUserName = function() { // do somethig } global var showUserAge = function(){ // do somethig } var validateUserForm = function() { // do somethig }
  • 51. - modulized functions - // users.js var users = {}; global users.showName = function () { // do somethig } users.showAge = function (){ // do somethig } users.validateForm = function () { // do somethig }
  • 52. - modulized functions - // users.js (function(global) { global.users = {}; global users.showName = function () { // do somethig } // ... )(this); improvement
  • 55. overwrite behavior - // using jQuery $(‘a#showDialog’).click(function() { $.ajax(‘/about’, { success: function(html) { // do something... } }); }); code smell
  • 56. overwrite behavior - // using jQuery $(‘a#showDialog’).click(function() { $.ajax($(this).attr(‘href’), { success: function(html) { // do something... } }); }); improvement
  • 58. shallow scope - solution 2 function → this
  • 59. shallow scope - // using jQuery var $elements = $(‘a#remote’); $elements.click(function() { var url = $(this).attr(‘href’); $.ajax(url, { success: function(html) { var text = $(html).text(); $element.text(text); } }); return false; });
  • 60. shallow scope - // using jQuery var $elements = $(‘a#remote’); $elements.click(function() { deep var url = $(this).attr(‘href’); $.ajax(url, { success: function(html) { var text = $(html).text(); $element.text(text); } }); return false; }); code smell
  • 61. shallow scope - // using jQuery var $elements = $(‘a#remote’); $elements.click(function() { var url = $(this).attr(‘href’); $.ajax(url, { success: function(html) { var text = $(html).text(); $(this).text(text); }, context: this }); return false; }); improvement
  • 62. DOM - DOM to model - problem DOM
  • 63. DOM - DOM to model - solution DOM
  • 64. DOM - DOM to model - var element = document.getElementById(‘message’); element.addEventListener(‘click’, function() { // this == element if (this.getAttribute(‘data-is-checked’)) { this.setAttribute(‘data-is-checked’, true); this.innerText = ‘clicked!’; } }); code smell
  • 65. DOM - DOM to model - var domToModel = function(element, Model) { var method, name, object, parent, proto; model = Object.create(element); proto = Model.prototype; for (name in proto) { method = proto[name]; model[name] = method; } Model.apply(model); return model; }; var CustomElement = function() {}; CustomElement.prototype.showText = function() { if (!this.getAttribute(‘data-is-checked’)) { var element = document.getElementById(‘message’); this.setAttribute(‘data-is-checked’, true); var model = domToModel(element, CustomElement); this.innerText = ‘clicked!’; model.addEventListener(‘click’, function() { } model.showText(); }; });
  • 66. DOM - DOM to model - var domToModel = function(element, Model) { var method, name, object, parent, proto; model = Object.create(element); proto = Model.prototype; for (name in proto) { method = proto[name]; model[name] = method; } Model.apply(model); return model; }; var CustomElement = function() {}; CustomElement.prototype.showText = function() { if (!this.getAttribute(‘data-is-checked’)) { var element = document.getElementById(‘message’); this.setAttribute(‘data-is-checked’, true); var model = domToModel(element, CustomElement); this.innerText = ‘clicked!’; model.addEventListener(‘click’, function() { } model.showText(); }; });
  • 67. DOM - DOM to model - var domToModel = function(element, Model) { var method, name, object, parent, proto; model = Object.create(element); proto = Model.prototype; for (name in proto) { method = proto[name]; model[name] = method; } Model.apply(model); return model; }; var CustomElement = function() {}; CustomElement.prototype.showText = function() { if (!this.getAttribute(‘data-is-checked’)) { var element = document.getElementById(‘message’); this.setAttribute(‘data-is-checked’, true); var model = domToModel(element, CustomElement); this.innerText = ‘clicked!’; model.addEventListener(‘click’, function() { } model.showText(); }; }); improvement
  • 68. - separate logic with view - problem
  • 69. - separate logic with view - solution
  • 70. - separate logic with view - function createTimer() { var timerId; var startTimer = function(millisec) { timerId = setTimeout(function() { $(‘.timeout’).text(â€˜ïŹnished’); }, millisec); } var stopTimer = function() { clearTimeout(timerId); } return { startTimer: startTimer, stopTimer: stopTimer } }
  • 71. - separate logic with view - function createTimer() { var timerId; var startTimer = function(millisec) { timerId = setTimeout(function() { $(‘.timeout’).text(â€˜ïŹnished’); view }, millisec); } var stopTimer = function() { clearTimeout(timerId); } return { startTimer: startTimer, stopTimer: stopTimer } } code smell
  • 72. - separate logic with view - function Timer(millisec) { this. millisec = millisec; this.callbacks = []; this.timerId = null; } Timer.prototype.afterFinish = function(callback) { return this.callbacks.push(callback); }; Timer.prototype.start = function() { var callbacks = this.callbacks; this.timerId = setTimeout(function() { var callback, i, length; for (i = 0, length = callbacks.length; i < length; i++) { var timer = new Timer(1000); callback = callbacks[i]; timer.afterFinish(function() { callback(); $('.timer .message').text('Finished!!'); } }); }, this. millisec); timer.start(); }; Timer.prototype.stop = function() { clearTimeout(this.timerId); }
  • 73. - separate logic with view - function Timer(millisec) { this. millisec = millisec; this.callbacks = []; } this.timerId = null; model Timer.prototype.afterFinish = function(callback) { return this.callbacks.push(callback); }; Timer.prototype.start = function() { view var callbacks = this.callbacks; this.timerId = setTimeout(function() { var callback, i, length; for (i = 0, length = callbacks.length; i < length; i++) { var timer = new Timer(1000); callback = callbacks[i]; timer.afterFinish(function() { callback(); $('.timer .message').text('Finished!!'); } }); }, this. millisec); timer.start(); }; Timer.prototype.stop = function() { clearTimeout(this.timerId); } improvement
  • 75.
  • 78.
  • 83.
  • 88.
  • 89. Shall we learn about Clean JavaScript?