This example will show how to use NanoQueue to decouple your components, or allow different modules, which are not aware of each other, to communicate through messages. This will allow you, or the community at large, to create some standard or commonly named messages one can publish or subscribe to.
Use the components below to demonstrate the messages being sent.
I'm publishing to the topic "calendar.data.new"!
(function(){
"use strict";
if(typeof _Q === "undefined"){
throw new Error("NanoQueue not found.");
}
class ModuleA {
constructor(nanoqueue){
this.q = nanoqueue;
this.name = this.constructor.name;
}
publishNewBooking(booking){
// Sample standardized format for new calendar bookings messages
var message = {
data : {
"bookings": [ booking ],
},
"created" : new Date().toISOString()
};
// Publish to the specified topic, supplying the data
this.q.publishTo("calendar.data.new", message);
}
doStuff(){
// Do some useful stuff to the input and build an object to share
// lets pretend we have gotten som data from a calendar service
var d = new Date();
var dateFrom = d.toISOString();
d.setHours(d.getHours() + 1);
var dateTo = d.toISOString();
var booking = {
"date-from" : dateFrom,
"date-to" : dateTo,
"subject" : "Test",
"body" : "This is a test"
};
// And we are publishing it!
this.publishNewBooking(booking);
}
}
var mod = new ModuleA(_Q);
_Q.registerModule(mod.name, mod);
})();
I'm listening for the topic "calendar.data.new"!
Still waiting...
(function(){
"use strict";
if(typeof _Q === "undefined"){
throw new Error("NanoQueue not found.");
}
class ModuleB {
constructor(nanoqueue){
this.q = nanoqueue;
// Using the class name for the module name, feel free to use something else.
this.name = this.constructor.name;
// Subscribe to the specified topic, supplying the callback
this.q.subscribeTo("calendar.data.new", this.updateUI.bind(this));
}
// message handler function
updateUI(data){
var selector = "#moduleB .result code";
var encodedData = JSON.stringify(data, null,'\t');
// do some important UI stuff, in this example we'll just display as JSON
document.querySelector(selector).innerHTML = encodedData;
// notify the world that we updated someting
var msg = {
node : {
selector : selector,
newValue : encodedData
},
canHighlight : true
};
this.q.publishTo("dom.node.change", msg);
}
}
var mod = new ModuleB(_Q);
_Q.registerModule(mod.name, mod);
})();