I have two javascript modules which act on different parts of the page. Now at moment as you can see I'm using the PubSubJS
library to publish and subscribe and transfer data if need be from one module to another module in a decoupled way. But I was thinking whether I can altogether omit the PubSubJS
library use JQuery promises(or any other native JQuery method) instead to achieve the same. I'm not so good with JQuery promises hence the need for this question. Can somebody provide me any better solution with JQuery.
var salesOrder = (function() {
"use strict";
var $root, $salesOrderNo, $closeButton;
var _init = function() {
$root = $("#sales-order")
$closeButton = $root.find("#close-button");
_attachEvents();
};
var _attachEvents = function() {
$closeButton.on("click", _closeSalesOrder);
};
var _closeSalesOrder = function() {
PubSub.publish("ui.unloadShell", "closed"); //Here I'm publishing
}
return {
init: _init
}
})();
$(document).ready(salesOrder.init);
And the second module as so
var erpTest = (function() {
"use strict";
var $root, $btnMenu, $shell;
var _init = function() {
$root = $("body")
$btnMenu = $root.find(".menu-button");
$shell = $root.find("#shell");
_attachEvents();
}
var _attachEvents = function() {
$btnMenu.on("click", _loadShell);
PubSub.subscribe('ui.unloadShell', _unloadShell); //Here I'm subscribing
}
var _loadShell = function(evt) {
var url = $(evt.target).data("url");
if (url && url.length) {
$shell.load(url, _loadCompleted);
}
};
var _unloadShell = function(evt, data) {
$shell.html(null); //Here is the subscribed handler
};
var _loadCompleted = function(evt) {
$.each([buttonModule.init, nameModule.init], function(index, func) {
func($shell);
});
};
return {
init: _init
}
})();
$(document).ready(erpTest.init);
I use the PubSub
pattern extensively. Your questions are the ones I was looking into a while ago. Here are my comments:
jQuery Promises
: Promises
are by nature async; do you really want an async channel of communication between components? Using Promises
, you'd expect that any subscribers respond properly as your publisher might take action back using .then
. Things will become complex as soon as you expect subscribers to respond accordingly to events.
jQuery has .on
, .off
, .one
to publish events; you simply need to pass {}
as aggregator. See that topic for further details: Passing an empty object into jQuery function. However jQuery
has some overhead compared to a simple pubSub/aggreagator
mechanism.
I built several labs of incremental complexity focused on the PubSub
pattern that you can consult below. LineApp
is the entry point.