JavaScriptをがんばるブログ

React,OSS,ソフトウェア開発が中心のブログです👨‍💻

ブレイクスルーjavascript: chp02-02 01

2015年発売の本だが、
es5 + jqueryでモーダルなどwebサイトでよく使うギミックのコーディングテクニックを紹介している本。
ツールフレームワークのHowToではなく、純粋にコーディングテクニックが学べる。
2015年秋頃に写経していて3ヶ月ほど休止していたが、javascript力の不足を感じ、またやりはじめた。

今は写真をクリックすると拡大画像がoverlayするlightboxのようなギミックを作っているところ。

http://ryota-murakami.github.io/breakthrough-javascript/Chapter2/chp02-02/01/

オブジェクトのイニシャライザでDOMのキャッシュとイベントハンドラのセットを行う書き方が新鮮で分かりやすいと思った。
完全なSPAでなければフレームワーク使わなくても、やり方次第で十分整理されたコードが書けそうですね。

function Modal(el) {
  this.initialize(el);
}

Modal.prototype.initialize = function(el) {
  this.$el = el;
  this.$container = $('#modal');
  this.$contents = $('#modal-contents');
  this.$close = $('#modal-close');
  this.$next = $('#modal-next');
  this.$prev = $('#modal-prev');
  this.$overlay = $('#modal-overlay');
  this.$window = $(window);
  this.index = 0;
  this.handleEvents();
};

Modal.prototype.handleEvents = function() {
  var self = this;
  this.$el.on('click', function(e) {
    self.show(e);
    return false;
  });
};

github.com