それマグで!

知識はカップより、マグでゆっくり頂きます。 takuya_1stのブログ

習慣に早くから配慮した者は、 おそらく人生の実りも大きい。

jQuery のlive / on / delegate がわからない

jqueryで作られたソースを見ていると、イベントについて、以下の3つが出てきて、ちょっと迷う。

live / on / delegate 

の使い分けを簡単に調べてみた。


delegate は on で置き換えられている

deleate は on にsuperseded(置き換えた)って書いてある。ただし互換性のために残ってるっぽい

$(elements).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(elements).on(events, selector, data, handler);        // jQuery 1.7+

on/delegateでそれぞれ違う書き方になった。

* Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. Similarly, events handled by.delegate() will propagate to the elements to which they are delegated; event handlers bound on any elements below it in the DOM tree will already have been executed by the time the delegated event handler is called. These handlers, therefore, may prevent the delegated handler from triggering by calling event.stopPropagation() or returning false.

通常ならイベントバブリングを止められないが、DOM上層へ向かってはlive()は一度だけ処理する、これほぼ同じことが、delegate にも起こるのだが、こっちは止まらない。delegate はセレクタ条件にマッチした、エレメントのイベントが発火したら動くことになる。たとえ動的に作られたエレメントでも、セレクタ条件にマッチすれば、イベントが登録済みから始まる。stopPropagation()やreturn false;で止めないと、DOM仮想で処理されたイベンドでもdocumentに向かって上層へどんどん伝播していくので、云々

http://api.jquery.com/delegate/

liveは更に古い

bind --> live ---> delegate --> on

となっているらしい。しかもliveはDeprecatedです。

これからは on を使おうってことらしい。

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

1.7以降ではon()が望ましい。なぜなら、以前のバージョンのbind()はDOMのイベントにダイレクトにアタッチしててて、アタッチするには、事前にDOMにエレメントがなくちゃダメだった。もっと柔軟にイベントハンドルをできるように on/delegateを使っていくことにした。

http://api.jquery.com/bind/


ってことらしい。

つまり、on/delegateを使うほうが、jQueryの恩恵に預かれるって単純な理解でいいか。

addEventListerが呼ばれるには、dom にノードがなくちゃいけないけど、on だと 登録のその時にノードはなくてもいい、イベント発火時した時にノードがあればあればいいってことですかね。