イベントを動的に追加、削除する
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.updateName = function(name) { | |
this.dispatchEvent({ | |
type: 'changeBefore', | |
data: this, | |
}); | |
this.name = name; | |
this.dispatchEvent({ | |
type: 'change', | |
data: this, | |
}); | |
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; | |
function logger(e) { | |
console.log(e); | |
$('#result').val(`${$('#result').val()}\n,change event. Name is ${e.data.name}`); | |
} | |
// この処理の内容がイベント通知に使われます | |
$('#update').on('click', function(e) { | |
observableArray.updateName($('#value').val()); | |
}); |
そしてこの関数をイベント通知に追加します。
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
$('#add').on('click', function(e) { | |
listner = observableArray.addEventListener('change', logger); | |
console.log(listner) | |
}); |
逆に削除する時にも関数を指定します。そのため処理を無名関数ではなく、関数化しておく必要があります。
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
$('#delete').on('click', function(e) { | |
observableArray.removeEventListener('change', logger); | |
}); |
addEventListenerを使ってイベントを購読し、removeEventListenerを使ってイベントの購読を解除します。その際、関数を指定する必要がありますので購読に使った関数をオブジェクトとして指定できる状態になっていなければなりません。無名関数では難しいのでご注意ください。
今回のコードはJSFiddleにアップロードされていますので実装時に参照してください。
コメントは受け付けていません。