SlideShare a Scribd company logo
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
Clean Javascript
I’m a programmer
@tricknotes
Clean Javascript
Clean JavaScript


http://www.flickr.com/photos/hoshikowolrd/5151171470/




                                                         Sapporo.js
SaCSS vol.29 - 2011.11.26                              (Ryunosuke SATO)
Clean Javascript
Clean Javascript
Clean Javascript
Clean Javascript
Clean Javascript
Clean Javascript
Clean Javascript
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
Clean Javascript
Clean Javascript
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
Clean Javascript
others...
Pure JavaScript
Clean Javascript
Application
https://gist.github.com/1362110
http://documentcloud.github.com/backbone/
http://www.sproutcore.com/
Clean Javascript
interest




http://www.flickr.com/photos/bonguri/4610536789/
reading
Good text
writing
Clean Javascript
Shall we learn
      about
Clean JavaScript?

More Related Content

What's hot (20)

Backbone.js
Backbone.jsBackbone.js
Backbone.js
Omnia Helmi
 
Integrating Angular js & three.js
Integrating Angular js & three.jsIntegrating Angular js & three.js
Integrating Angular js & three.js
Josh Staples
 
Developing large scale JavaScript applications
Developing large scale JavaScript applicationsDeveloping large scale JavaScript applications
Developing large scale JavaScript applications
Milan Korsos
 
Javascript MVVM with Vue.JS
Javascript MVVM with Vue.JSJavascript MVVM with Vue.JS
Javascript MVVM with Vue.JS
Eueung Mulyana
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widget
Tudor Barbu
 
jQuery Internals + Cool Stuff
jQuery Internals + Cool StuffjQuery Internals + Cool Stuff
jQuery Internals + Cool Stuff
jeresig
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
David Ličen
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
jeresig
 
MVC pattern for widgets
MVC pattern for widgetsMVC pattern for widgets
MVC pattern for widgets
Behnam Taraghi
 
Client Side MVC & Angular
Client Side MVC & AngularClient Side MVC & Angular
Client Side MVC & Angular
Alexe Bogdan
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
Tudor 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 HMR
Javier 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 JavaScript
Tim Perry
 
Js unit testing
Js unit testingJs unit testing
Js unit testing
Mihail Irintchev
 
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.js
Javier Lafora Rey
 
Test slideshare document
Test slideshare documentTest slideshare document
Test slideshare document
Luckner Jean-Baptiste
 
Basic Tutorial of React for Programmers
Basic Tutorial of React for ProgrammersBasic Tutorial of React for Programmers
Basic Tutorial of React for Programmers
David Rodenas
 
Integrating Angular js & three.js
Integrating Angular js & three.jsIntegrating Angular js & three.js
Integrating Angular js & three.js
Josh Staples
 
Developing large scale JavaScript applications
Developing large scale JavaScript applicationsDeveloping large scale JavaScript applications
Developing large scale JavaScript applications
Milan Korsos
 
Javascript MVVM with Vue.JS
Javascript MVVM with Vue.JSJavascript MVVM with Vue.JS
Javascript MVVM with Vue.JS
Eueung Mulyana
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widget
Tudor Barbu
 
jQuery Internals + Cool Stuff
jQuery Internals + Cool StuffjQuery Internals + Cool Stuff
jQuery Internals + Cool Stuff
jeresig
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
David Ličen
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
jeresig
 
MVC pattern for widgets
MVC pattern for widgetsMVC pattern for widgets
MVC pattern for widgets
Behnam Taraghi
 
Client Side MVC & Angular
Client Side MVC & AngularClient Side MVC & Angular
Client Side MVC & Angular
Alexe Bogdan
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
Tudor 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 HMR
Javier 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 JavaScript
Tim 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 Programmers
David Rodenas
 

Similar to Clean Javascript (20)

Unit Testing in JavaScript with MVC and QUnit
Unit Testing in JavaScript with MVC and QUnitUnit Testing in JavaScript with MVC and QUnit
Unit Testing in JavaScript with MVC and QUnit
Lars Thorup
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
Bert Wijnants
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Library
jeresig
 
jQuery
jQueryjQuery
jQuery
Ivano Malavolta
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
Todd Anglin
 
CT presentatie JQuery 7.12.11
CT presentatie JQuery 7.12.11CT presentatie JQuery 7.12.11
CT presentatie JQuery 7.12.11
virtualsciences41
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 
Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScript
ryanstout
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
Andrew Dupont
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
Quinton Sheppard
 
Cleaner, Leaner, Meaner: Refactoring your jQuery
Cleaner, Leaner, Meaner: Refactoring your jQueryCleaner, Leaner, Meaner: Refactoring your jQuery
Cleaner, Leaner, Meaner: Refactoring your jQuery
Rebecca Murphey
 
Javascript And J Query
Javascript And J QueryJavascript And J Query
Javascript And J Query
itsarsalan
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
Michael Girouard
 
User Interface Development with jQuery
User Interface Development with jQueryUser Interface Development with jQuery
User Interface Development with jQuery
colinbdclark
 
Web Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performance
johndaviddalton
 
Intro to jQuery @ Startup Institute
Intro to jQuery @ Startup InstituteIntro to jQuery @ Startup Institute
Intro to jQuery @ Startup Institute
Rafael Gonzaque
 
Gitter marionette deck
Gitter marionette deckGitter marionette deck
Gitter marionette deck
Mike Bartlett
 
Prototype Framework
Prototype FrameworkPrototype Framework
Prototype Framework
Julie Iskander
 
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
Jarod Ferguson
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
Ara Pehlivanian
 
Unit Testing in JavaScript with MVC and QUnit
Unit Testing in JavaScript with MVC and QUnitUnit Testing in JavaScript with MVC and QUnit
Unit Testing in JavaScript with MVC and QUnit
Lars Thorup
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
Bert Wijnants
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Library
jeresig
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
Todd Anglin
 
CT presentatie JQuery 7.12.11
CT presentatie JQuery 7.12.11CT presentatie JQuery 7.12.11
CT presentatie JQuery 7.12.11
virtualsciences41
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 
Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScript
ryanstout
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
Andrew Dupont
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
Quinton Sheppard
 
Cleaner, Leaner, Meaner: Refactoring your jQuery
Cleaner, Leaner, Meaner: Refactoring your jQueryCleaner, Leaner, Meaner: Refactoring your jQuery
Cleaner, Leaner, Meaner: Refactoring your jQuery
Rebecca Murphey
 
Javascript And J Query
Javascript And J QueryJavascript And J Query
Javascript And J Query
itsarsalan
 
User Interface Development with jQuery
User Interface Development with jQueryUser Interface Development with jQuery
User Interface Development with jQuery
colinbdclark
 
Web Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performance
johndaviddalton
 
Intro to jQuery @ Startup Institute
Intro to jQuery @ Startup InstituteIntro to jQuery @ Startup Institute
Intro to jQuery @ Startup Institute
Rafael Gonzaque
 
Gitter marionette deck
Gitter marionette deckGitter marionette deck
Gitter marionette deck
Mike Bartlett
 
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
Jarod Ferguson
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
Ara Pehlivanian
 
Ad

More from Ryunosuke SATO (17)

片手間JS on Rails
片手間JS on Rails片手間JS on Rails
片手間JS on Rails
Ryunosuke 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 MVC
Ryunosuke 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
ServerSideJavaScript
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 MVC
Ryunosuke 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
 
Ad

Recently uploaded (20)

GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
Grannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI ExperiencesGrannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI Experiences
Lauren Parr
 
Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Aaryan Kansari
 
Evaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical ContentEvaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical Content
Paul Groth
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Gihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai TechnologyGihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai Technology
zainkhurram1111
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Nikki Chapple
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
Introducing FME Realize: A New Era of Spatial Computing and AR
Introducing FME Realize: A New Era of Spatial Computing and ARIntroducing FME Realize: A New Era of Spatial Computing and AR
Introducing FME Realize: A New Era of Spatial Computing and AR
Safe Software
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
Dev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API WorkflowsDev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API Workflows
UiPathCommunity
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
Create Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent BuilderCreate Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent Builder
DianaGray10
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
Grannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI ExperiencesGrannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI Experiences
Lauren Parr
 
Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Aaryan Kansari
 
Evaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical ContentEvaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical Content
Paul Groth
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Gihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai TechnologyGihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai Technology
zainkhurram1111
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Nikki Chapple
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
Introducing FME Realize: A New Era of Spatial Computing and AR
Introducing FME Realize: A New Era of Spatial Computing and ARIntroducing FME Realize: A New Era of Spatial Computing and AR
Introducing FME Realize: A New Era of Spatial Computing and AR
Safe Software
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
Dev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API WorkflowsDev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API Workflows
UiPathCommunity
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
Create Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent BuilderCreate Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent Builder
DianaGray10
 

Clean Javascript

  • 2. Community for people who like JavaScript. Sapporo.js
  • 23. JavaScript is most popular!
  • 27. ? ? How to face the difficulty
  • 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
  • 89. Shall we learn about Clean JavaScript?