hifiveのイベント通知機能を使おう
Webシステムの開発時においてイベント通知はよく使われます。例えばjQueryでボタンを押した時のイベントは次のように設定されます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('button').on('click', function(e) { | |
// 何かの処理 | |
}); |
こうした通知機能を任意のオブジェクトに追加できるのがhifiveのイベント通知機能になります。今回はその基本的な実装方法について紹介します。
mixを使う
まずオブジェクトに対して eventDispatcher を追加します。これは Prototype に対して追加します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ObservableArray() { | |
}; | |
h5.mixin.eventDispatcher.mix(ObservableArray.prototype); |
次にそのオブジェクトのインスタンスを作ります。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var observableArray = new ObservableArray; |
この時点でインスタンスに対して addEventListener / removeEventListener が追加されています。通知を受け取るイベント名を設定し、その後実行する処理内容を記述します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
observableArray.addEventListener('changeBefore', function(e) { | |
console.log('changeBefore', e); | |
}); | |
observableArray.addEventListener('change', function(e) { | |
console.log('change', e); | |
}); |
後は任意のタイミングで dispatchEvent を実行します。typeとしてイベントの名前、後は任意のハッシュキーでデータを送れます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
observableArray.dispatchEvent({ | |
type: 'change', | |
data: this, | |
}); |
イベント通知は複数の関数を設定できます。イベント通知、いわゆるPubSub型であればオブジェクト側では処理した後に何の関数を呼び出すかといった意識をする必要がありません。各クラスのメソッドに追加しておくことで、オブジェクト間の通信がスムーズになることでしょう。
今回のコードはJSFiddleにアップロードしてあります。実装時の参考にしてください。
コメントは受け付けていません。