ようへい

2013年7月18日木曜日

非推奨になった Mutation events を Mutation Observers に置き換えよう

前からDOM3(黒い三連星じゃないよ)で実装されたDOMAttrModifiedや、DOMNodeInsertedをGreasemonkeyスクリプト内で使用していたのだが、これらのMutation eventsが非推奨となってしまったらしい。
じゃあ何を使ったらいいの?ということで、Mutation ObserversというAPIが提供されているらしい。 Mutation Observersの利用方法をまとめてみた。

ちょっと読んでみよう

使う前に、どうやって使うかなど、ちょっと頭に入れておこう。
Mozillaのページにまとめて書いてあるので、そちらを見れば大丈夫かと。
MutationObserver - Web API リファレンス | MDN
https://developer.mozilla.org/ja/docs/Web/API/MutationObserver MutationObserverにメソッドを与えてインスタンスを作成。
インスタンスメソッドのobserve実行時のオプションで、監視する種類などを設定すると。フムフム。

MutationObserverはこう使う

コードを見た方が速いので、まずは使い方から。
たとえば、DOMAttrModifiedMutationObserverに置き換えるとこんな感じ。
$('#hoge').bind('DOMAttrModified',function(event){
  console.dir(event);
});
var mo = new MutationObserver(function(mutationRecords){
  console.dir(mutationRecords);
});
mo.observe($('#hoge').get(0), {attributes: true});
変更前の値も欲しいならこう
var mo = new MutationObserver(function(mutationRecords){
  console.dir(mutationRecords);
});
mo.observe($('#hoge').get(0), {attributes: true, attributeOldValue: true});

Mutation eventsからMutationObserverへ移行しよう

こんな感じかな。
Mutation events Mutation Observers
DOMAttrModified observe( Node target, {attributes: true, attributeOldValue: true} );
DOMNodeInserted observe( Node target, {childList: true} );
DOMNodeRemoved observe( Node target, {childList: true} );
DOMCharacterDataModified observe( Node target, {characterData: true, characterDataOldValue: true} );
DOMSubtreeModified observe( Node target, {subtree: true} );
そして Firefox、Chromeは実装しているけど、Internet Explorerは未実装らしい。さすがやで!期待を裏切らない。それでこそIE。
IEは消費電力で勝負ですもんね。
よいこのみんな!夏は消費電力を抑えるためにIEを使おうね (オイ)
Internet Explorer 10の消費電力はChromeやFirefoxより18%低い, とMicrosoftは主張 | TechCrunch Japan
http://jp.techcrunch.com/2013/06/06/20130605microsoft-internet-explorer-10-is-the-most-energy-efficient-browser-uses-up-to-18-less-power-than-chrome-and-firefox/
関連記事