の配列項目(機能)を取得する方法(https://davidwalsh.name/pubsub-javascriptから抽出):ES6 - 次のようにES6を使用して、パブリッシュ・サブスクライブパターンを考えると、特定のコンテキスト
class PubSub {
constructor() {
this.handlers = [];
}
subscribe(event, handler, context) {
if (typeof context === 'undefined') {
context = handler;
}
{
if (this.getHandler(event, handler) == null) {
this.handlers.push({event: event, handler: handler.bind(context), key: Guid()});
}
}
}
unsubscribe(event, handler) {
let filteredHandler = this.getHandler(event, handler);
if (filteredHandler != null) {
let idx = this.handlers.indexOf(filteredHandler);
if (idx > -1) {
this.handlers.splice(idx, 1);
}
}
}
publish(event, args) {
this.handlers.forEach(topic => {
if (topic.event === event) {
topic.handler(args)
}
})
}
getHandler(event, handler) {
if (this.handlers == null || this.handlers.length < 1) {
return null;
}
let filtered = null;
this.handlers.forEach(topic => {
if (topic.event === event && topic.handler === handler) {
filtered = topic;
}
});
return filtered;
}
getNumOfSubsribers() {
if (this.handlers != null && this.handlers.length > 0) {
return this.handlers.length;
}
return 0;
}
}
購読およびパブリッシュ方法が働きます。ただし、getHandlerおよびunsubscribeメソッドは期待通りに機能しません(getHandlerはnullを返すようです)。私は検索しようとしましたが、この問題(満足している解決策を得ることができませんでした(特定のコンテキストにバインドされた関数がどのように配列から除外されるかは不明です)。
私はコードで何が間違っていますか?親切にgetHandlerについて私に助言し、コードの一部を退会してください。
何か助けてください。
あなたが購読した後、「ハンドラー」は何になるのですか?空かヌルですか?それが空であれば、何かがサブスクリプションコードに間違っているか、サブスクリプションコードに間違ったものが与えられています。ハンドラがnullでない場合、getハンドラコードに何か問題があります。または、元のサブスクリプションで何か問題が発生し、コードがハンドラを見つけられなくなります(nullイベントを送信する場合など)。 –
返されたハンドラがnullであることが判明しました。私は、正しいコンテキストにバインドされた正しいハンドラを取得することを期待していました。この結果で、私はunsubscribeメソッドで指定されたハンドラリストから削除したかったのです。 – oatcrunch