postaljs / postal.js

JavaScript pub/sub library supporting advanced subscription features, and several helpful add-ons.
http://ifandelse.com
MIT License
2.83k stars 193 forks source link

How to publish data between Node.js modules? #165

Closed bennycode closed 7 years ago

bennycode commented 7 years ago

Hello, I have two node modules (A & B).

In Node module A I have a Class A which defines the following:

module_a\ClassA.js

ClassA.prototype.postEvent = function() {
  postal.subscribe({
    channel: "my-channel",
    topic: "my-topic",
    callback: function(data, envelope) {
      console.log('Received data in Module A.', data, envelope);
    }
  });

  postal.publish({
    channel: "my-channel",
    topic: "my-topic",
    data: {
      text: 'Hello World!'
    }
  });
}

As you can see, Class A subscribes to a topic and then publishes data for this specific topic.

Now I want to subscribe to the same topic in module B (which initiates Class A from module A):

module_b\app.js

var ModuleA = require('module_a');
var postal = require('postal');

postal.subscribe({
  channel: "my-channel",
  topic: "my-topic",
  callback: function(data, envelope) {
    console.log('Received data in Module B.', data, envelope);
  }
});

var classA = new ModuleA.ClassA();
classA.postEvent();

Unfortunately, the subscription of Module B doesn't get invoked when calling classA.postEvent();. Only Class A's subscription gets invoked.

Can you tell me what I am doing wrong? Do I have to take care of something additional when publishing events for other Node.js modules?

ifandelse commented 7 years ago

@bennyn - quick question, are both modules pulling in the same version of postal? (i.e. - are these separate npm modules that have different version ranges of postal in their package.json?)

bennycode commented 7 years ago

@ifandelse That was exactly the issue!

I declared postal in the package.json files of both modules. But because ModuleB is using ModuleA, it receives postal already as transitive dependency from ModuleA, so I don't need to declare postal as dependency again in the package.json file of ModuleB (in fact this causes problems, having both modules using different postal instances).

Thank you for your help! Now I am eagerly waiting for postal v2.0.5. 😃

Thumbs up and keep the good work!

Will close this issue here as solved. 👍