dimanche 26 mars 2017

ES6 - How to get array item (function) of a specific context

Given a publish-subscribe pattern using ES6 as follows (extracted from http://ift.tt/20wYK9e):

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;
    }
}

The subscribe and publish methods work. However, the getHandler and unsubscribe method do not work as expected (getHandler seems returning null). I have tried to search around but could not get a satisfactory solution to this problem (not sure how a function bound to a given context can be filtered out from an array).

What have I done wrong in the code? Kindly advise me on getHandler and also unsubscribe part of the code.

Appreciate some kind help.

Aucun commentaire:

Enregistrer un commentaire