user896715
user896715

Reputation: 109

Javascript PubSub Scope Issue

im having an issue with PubSub in Javascript. im trying to figure out why $.subscribe is not printing the value. I assume its because of scope between $.publish and $.subscribe.

i would like to have other modules subscribe to the event. how would i do that? i put an example on jsfiddle:

http://jsfiddle.net/Fvk2G/

window.MQ = (function (window, document, undefined) {

    "use strict";

    function MQ() {

        testPubSub();

        function testPubSub() {
            $.publish("test");
        }
    }

    return MQ

})(this, this.document);

var mq = new MQ();

$.subscribe("test", function () {
    console.log("print value");
});

thanks

pete

Upvotes: 1

Views: 185

Answers (1)

Pointy
Pointy

Reputation: 413737

You've set up a system that uses jQuery event handling for relaying messages, which is not in itself a bad idea. If you expect that it will save events that were triggered and report them to subsequent "subscribers", however, you've made an incorrect assumption about the semantics of the event mechanism. If a tree falls in the forest, the forest doesn't retain the sound until your hiking party arrives. Similarly, an event that's triggered with no listeners is just forgotten.

If you move your code that creates the "MQ" to after the subscription is done, then it works fine.

Upvotes: 1

Related Questions