mercredi 3 février 2016

Pub/Sub does not work in JavaScript

I am implementing simple pub/sub layer in my current project. I am using requirejs for AMD approach. I have following modules.

// App, fires both modules in the beginning
define(['ModuleA', 'ModuleB'], function (ModuleA, ModuleB) {

    'use strict';

    var App = function () {
        this.init();
    };

    App.prototype = (function () {

        var init = function () {
            new ModuleA();
            new ModuleB();
        };

        return {
            init: init
        };

    })();

    return App;
});

ModuleA is below

// ModuleA
define(['EventBus'], function (EventBus) {

    'use strict';

    var ModuleA = function () {
        this.Event = new EventBus();
        this.$audioContainer.addEventListener('click', this.foo.bind(this));
    };

    ModuleA.prototype = (function () {

        var self = this;

        var foo = function () {
            console.log('FOO'); // display FOO on console
            this.Event.subscribe('event/click');
        };

        return {
            foo: foo
        };

    })();

    return ModuleA;
});

ModuleB is below

// ModuleB
define(['EventBus'], function (EventBus) {

    'use strict';

    var ModuleB = function () {
        this.Event = new EventBus();
    };

    ModuleB.prototype = (function () {

        var self = this;

        var bar = function () {
            console.log('bar');
            this.Event.publish('event/click', star);
        },

        star = function () {
            console.log('STAR'); // Does not log in console
        };

        return {
            bar: bar,
            star: star
        };

    })();

    return ModuleB;
});

and below is my EventBus module that is pub/sub

define(function () {

    'use strict';

    var EventBus = function () {
        this.subscribers = {};
    };

    EventBus.prototype = (function () {

        subscribe = function (eventName, callback) {
            if (!this.subscribers[eventName]) this.subscribers[eventName] = [];

            this.subscribers[eventName].push(callback);
        },

        publish = function (eventName, dataObject) {
            if (!this.subscribers[eventName] || this.subscribers[eventName].length < 1) return;
            this.subscribers[eventName].forEach(function(listener) {
                listener(dataObject || {});
            });
        };

        return {
            publish: publish,
            subscribe: subscribe
        };

    })();

    return EventBus;
});

Somehow my pubsub does not work. It does not show any error in console. I think the problem is that I am initializing both modules i.e. ModuleA and ModuleB in App at the same time. It does subscribe successfully in ModuleA however, it does not publish in ModuleB.

How can I fix this?

Aucun commentaire:

Enregistrer un commentaire