This is Peter Higgins’s pub sub library: https://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js
(function (d) {
var cache = {};
d.publish = function (topic, args) {
cache[topic] && d.each(cache[topic], function () {
this.apply(d, args || []);
});
};
d.subscribe = function (topic, callback) {
if (!cache[topic]) {
cache[topic] = [];
}
cache[topic].push(callback);
return [topic, callback];
};
d.unsubscribe = function (handle) {
var t = handle[0];
cache[t] && d.each(cache[t], function (idx) {
if (this == handle[1]) {
cache[t].splice(idx, 1);
}
});
};
})(jQuery);
I don’t understand the logic and the functionality of publish:
cache[topic] && d.each(cache[topic], function () {
**this.apply(d, args || []);** //what is happening here?
});
What is the purpose of this part? except the fact that it publishes the event
In this context, the
&&is used as a shorthand for:This is because
&&(and||) are short-circuiting, so if the left hand side evaluates to afalse-ish value (ortrue-ish value, in the case of||), the right hand side does not get evaluated.For example:
> function foo(result) { console.log("foo"); return result; } > function bar(result) { console.log("bar"); return result; } > foo(false) && bar(true); foo false