イベントを自動判定する

2010年 8月 20日

タッチパネルに対応するアプリケーションを開発する場合、開発は従来のマウスを使うブラウザ環境で行いつつ検証を実機でという手順を繰り返すことになるが、その際にイベントハンドラに記述するマウスイベントとタッチイベントの切り替えを自動的に判定して行う方法を Apple が公開している iAd のサンプルコード内に見つけたので開発しているアプリケーションのコードに適用した。

const BGPSupportsTouches = ("createTouch" in document);
const BGPStartEvent = BGPSupportsTouches ? "touchstart" : "mousedown";
const BGPMoveEvent  = BGPSupportsTouches ? "touchmove"  : "mousemove";
const BGPEndEvent   = BGPSupportsTouches ? "touchend"   : "mouseup";

このように定義しておいて次の様な例で使うと、実機に移植する際に一々コードを置換修正する必要がなくなって便利この上ない。

Anode.addEventListener(BGPStartEvent, this, false);