🍃このブログは移転しました。
3秒後、自動的に移動します・・・。

addEventListenerのhandleEventオブジェクト

これはちょっと自分の中で衝撃的すぎたのでメモ。

参考:addEventListener, handleEvent and passing objects | The CSS Ninja - All things CSS, JavaScript & HTML

こんなんアリなんかー!w

handleEventって用意しておけば

var Swiper = function(element) {
  this.elm = element;

  // touchstartでthis・・・this??
  this.elm.addEventListener('touchstart',  this, false);
  this.elm.addEventListener('touchmove',   this, false);
  this.elm.addEventListener('touchend',    this, false);
  this.elm.addEventListener('touchcancel', this, false);
};

Swiper.prototype = {
  // なんやかんや...
  // そのthis、実は私のことだ!
  handleEvent: function(ev) {
    switch (ev.type) {
    case 'touchstart':   this.onTouchStart(ev); break;
    case 'touchmove':    this.onTouchMove(ev);  break;
    case 'touchcancel':
    case 'touchend':     this.onTouchEnd(ev);   break;
  }
};

バインドしたオブジェクトが、handleEventって関数をもってれば、
イベントリスナーではthisってするだけで拾ってくれる!

今までソレ用に関数を用意してたけど、これからはちょっとだけコードが短くなるー。
ハンドラをひとつにまとめられるので、イベント剥がす時も楽ちん。