SlideShare une entreprise Scribd logo
1  sur  89
Télécharger pour lire hors ligne
Clean JavaScript


http://www.flickr.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.flickr.com/photos/hoshikowolrd/5151171470/




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




                interesting!
I like
JavaScript is most popular!
but...
http://www.flickr.com/photos/maynard/6105929170/




                              difficult
Now training...
?
                     ?
How to face the difficulty
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(‘finished’);
    }, 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(‘finished’);      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.flickr.com/photos/bonguri/4610536789/
reading
Good text
writing
Shall we learn
      about
Clean JavaScript?

Contenu connexe

Tendances

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
 
Basic Tutorial of React for Programmers
Basic Tutorial of React for ProgrammersBasic Tutorial of React for Programmers
Basic Tutorial of React for ProgrammersDavid Rodenas
 

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

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

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

Plus de Ryunosuke SATO

Ember コミュニティとわたし
Ember コミュニティとわたしEmber コミュニティとわたし
Ember コミュニティとわたし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
 

Plus de 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
 

Dernier

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
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 businesspanagenda
 
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 SavingEdi Saputra
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - 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
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
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...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
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 AmsterdamUiPathCommunity
 
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 educationjfdjdjcjdnsjd
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
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...DianaGray10
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
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...Jeffrey Haguewood
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
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, ...Angeliki Cooney
 
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
 

Dernier (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
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
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - 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
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 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...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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
 
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
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
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...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
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...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
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, ...
 
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
 

Clean Javascript

  • 1. Clean JavaScript http://www.flickr.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.flickr.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 difficulty
  • 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(‘finished’); }, 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(‘finished’); 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?