LoginSignup
11
10

More than 5 years have passed since last update.

jQuery Event Delegation の代替えを考える

Last updated at Posted at 2015-03-05

jQuery Event Delegationとは?

$('body').on('click', 'button', handleButtonClicks)

function handleButtonClicks(event) {
    console.log(event.target.id, 'button clicked!')
}

みたいなやつです。
動くサンプル

親要素へのイベントハンドラで、子要素のイベントが拾えます。

何が嬉しいのか?

例えば、Todoリストのdoneチェックボックスを考えてみましょう。

DOM要素それぞれにイベントハンドラを設定すると

Todoの項目を追加して、DOM要素を増やすと
DOM要素を増やすたびにイベントハンドラを設定します。

Event Delegationを使うと

最初に一回だけ親要素にイベントハンドラを設定します。
子要素が増えても同じイベントハンドラで対応します。

詳しいことはUnderstanding Event Delegation | jQuery Learning Centerを読んでください。

jQueryに代わるもの

Finacial TimesFT Labs製の
ftlabs/ftdomdelegateというライブラリがあります。

こんな風に使います

<script src="http://wzrd.in/standalone/dom-delegate@latest"></script>
<script>
    document.addEventListener("DOMContentLoaded", main)

    function main() {
        domDelegate(document.body).on('click', 'button', handleButtonClicks)
        document.body.innerHTML = '<button>ボタン</button>'
    }

    function handleButtonClicks(event) {
        console.log('click', event)
    }
</script>

動くサンプル

Event Delegationを実現する仕組み

ソースを見るとElement.matches APIを使っています。

matchesの具体的な使い方は、以下のブログが詳しいです。
Selectors APIのmatchesSelectorと、動的なページでのイベント処理 - 素人がプログラミングを勉強していたブログ

11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10