イベント処理を複数記述、実行する
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のイベント通知機能になります。今回は複数のイベントを設定する方法を紹介します。
サンプル
よくある例として、クラスの値を変更する前と後でイベントを発行するものがあります。そうした実装を行う際には次のように行います。
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() { | |
this.name = 'Init'; | |
}; | |
ObservableArray.prototype.nameChange = function(name) { | |
this.dispatchEvent({ | |
type: 'changeBefore', | |
data: this, | |
}); | |
this.name = name; | |
this.dispatchEvent({ | |
type: 'change', | |
data: this, | |
}); | |
} | |
h5.mixin.eventDispatcher.mix(ObservableArray.prototype); |
実際の処理を行う前と後で2回 dispatchEvent を実行します。後はそれぞれを購読するメソッドを定義します。
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; | |
observableArray.addEventListener('changeBefore', function(e) { | |
$('#result').val(`${$('#result').val()}\n,changeBefore event..name is ${e.data.name}`); | |
}); | |
observableArray.addEventListener('change', function(e) { | |
$('#result').val(`${$('#result').val()}\n,change event..name is ${e.data.name}`); | |
}); | |
observableArray.addEventListener('change', function(e) { | |
$('#result').val(`${$('#result').val()}\n,another change event..name is ${e.data.name}`); | |
}); | |
observableArray.nameChange('Hello'); |
イベントを購読する処理は複数書いておくことができます。こうすることで、購読される側はどの処理が購読しているのかを一切気にする必要なく、単にdispatchEventを実行すれば良いだけになります。コールバック処理の場合は一つの関数しか実行できませんがdispatchEventであれば購読しているイベントすべてに通知が飛びます。
今回のコードはJSFiddleにて確認できます。イベントの通知処理の方法について確認してください。
コメントは受け付けていません。