たれぱんのびぼーろく

わたしの備忘録、生物学とプログラミングが多いかも

d3.js Events version 4

d3.js version 4における、Eventの使い方・原理まとめ.

イベントリスナ

DOM living standardにおける、addEventListener()にselection.on()が対応する.

.on(typenames[, listener[, capture]])

typenames = click[.optionalName][ otherEvent]
typenameの後に、".potionalName"の形で名前を付けられる.
単一typenameイベントに対し、複数のイベントリスナをつける場合、違う名前で登録する(click.foo, click.bar)
また、同時に複数のtypenameに対しイベントリスナを付加できる。"click drag"みたいな形で、空白を入れて登録.

listenerの引数
listener(d, i, nodes)
thisはcurrent_DOM_element

being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element.

Eventはなんと、listenerへ明示的には渡されない!!
d3.Eventオブジェクトを介してアクセスする(なんとなく気持ち悪い)
d3.Eventは、eventListenerが動いている間、届いたDOMEventになっている。listenerが終了すると、リセットされる.

To access the current event within a listener, use d3.event.
...
This is set during the invocation of an event listener, and is reset after the listener terminates.

github.com

Drag

Dragビヘイビアはオブジェクトであり、関数でもある. d3.drag()がコンストラクタ.
drag(selection)またはselection.call(drag)で特定の要素へ結び付けられる.

The returned behavior, drag, is both an object and a function, and is typically applied to selected elements via selection.call. d3.js API reference

drag.on(typename[,listener])

The type must be one of the following:

  • start - after a new pointer becomes active (on mousedown or touchstart).
  • drag - after an active pointer moves (on mousemove or touchmove).
  • end - after an active pointer becomes inactive (on mouseup, touchend or touchcancel).

the current datum d and index i, with the this context as the current DOM element.

たぶん(精査してないけど)d3.dispatchを利用した、自作Eventがdragの正体.
dragがEventで、drag.onがsekection.onに相当しているはず.
referenceにもそれっぽいこと書いてあったから、暇があったら精査.
あと, 自作イベントの必要性も要精査.