Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@foundit/broadcasterjs

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@foundit/broadcasterjs - npm Package Compare versions

Comparing version 1.1.1 to 1.1.2

55

dist/esm/index.js

@@ -31,3 +31,3 @@ var __assign = (this && this.__assign) || function () {

if (!options.useLatestSubscriberScope)
return id;
return null;
// Remove previous listener and set new to update scope.

@@ -46,4 +46,7 @@ off([type, listener, { suppressDebug: true }]);

var eventTarget = createOrGetCustomEventNode(hubId);
eventTarget.addEventListener('broadcast-' + type, listener);
return id;
var unbind = helpers().bind(eventTarget, {
type: ('broadcast-' + type),
listener: listener,
});
return unbind;
};

@@ -63,7 +66,15 @@ var once = function (_a) {

var eventTarget = createOrGetCustomEventNode(hubId);
eventTarget.addEventListener('broadcast-' + type, listener, { once: true });
return id;
var unbind = helpers().bind(eventTarget, {
type: ('broadcast-' + type),
listener: listener,
options: { once: true },
});
return unbind;
};
var off = function (_a) {
var type = _a[0], listener = _a[1], _b = _a[2], settings = _b === void 0 ? defaultSettings : _b;
var _b;
var type = _a[0], listener = _a[1], _c = _a[2], settings = _c === void 0 ? defaultSettings : _c;
if (typeof ((_b = listener) === null || _b === void 0 ? void 0 : _b.prototype) === 'undefined') {
throw new Error('Listener function not passed as a reference will not match previously set Broadcast listener.');
}
var options = setOptions(settings);

@@ -165,3 +176,10 @@ debugmode({

};
return { serializeFn: serializeFn, hashCode: hashCode };
var bind = function (target, _a) {
var type = _a.type, listener = _a.listener, options = _a.options;
target.addEventListener(type, listener, options);
return function unbind() {
target.removeEventListener(type, listener, options);
};
};
return { serializeFn: serializeFn, hashCode: hashCode, bind: bind };
}

@@ -183,11 +201,13 @@ function debugmode(_a) {

START SUBSCRIPTION IN REACT
Return the `off` function if it is desired to stop subscription on unmount.
useEffect(() => {
broadcast.on(['BROADCAST-ID', flagReceivedFunction])
}, [flagReceivedFunction])
const off = broadcast.on(['BROADCAST-ID', myCallbackFunction])
return off
}, [myCallbackFunction])
START SUBSCRIPTION VANILLA JS
broacast.on(['BROADCAST-ID', ({ detail }) => {
const off = broacast.on(['BROADCAST-ID', ({ detail }) => {
document.body.append(detail + ' ');
}]);
broacast.once(['BROADCAST-ID', ({ detail }) => {
const off = broacast.once(['BROADCAST-ID', ({ detail }) => {
document.body.append(detail + ' ');

@@ -197,7 +217,5 @@ }]);

END SUBSCRIPTION
broacast.off(['BROADCAST-ID', ({ detail }) => {
document.body.append(detail + ' ');
}]);
Execute the function returned by the subscribe function.
PUBLISH IN REACT & VANILLLA JS
PUBLISH (REACT & VANILLLA JS)
broadcast.emit('BROADCAST-ID', 'Hello world')

@@ -212,3 +230,3 @@

Advanced: on,once,off takes an optional third value and emit takes
Advanced: function `on` and `once` takes an optional third value and emit takes
an optional third argument in the form of a settings object.

@@ -219,5 +237,6 @@ {

allowDoublettesSubscribers: boolean
useLatestSubscriberScope: true,
suppressDebug: false,
useLatestSubscriberScope: true, // <- internal use
suppressDebug: false, // <- internal use
}
There is also an 'off' function that unsubscribes but it is not pushed forward since for it to work you need to have the exact same listener sent in, passed by reference. The return function of the 'on' and 'once' takes care of that behind the scene automatically.
*/

@@ -0,6 +1,20 @@

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var _a;
let broadcastItemsCache = [];
let globalDebug = ((_a = new URLSearchParams(window.location.search).get('debug')) === null || _a === void 0 ? void 0 : _a.toLowerCase()) ===
Object.defineProperty(exports, "__esModule", { value: true });
exports.broadcast = void 0;
var broadcastItemsCache = [];
var globalDebug = ((_a = new URLSearchParams(window.location.search).get('debug')) === null || _a === void 0 ? void 0 : _a.toLowerCase()) ===
'broadcasterjs';
const defaultSettings = {
var defaultSettings = {
debug: false,

@@ -12,7 +26,8 @@ debugGlobal: false,

};
const eventBus = () => {
const hubId = ' broadcast-node ';
const on = ([type, listener, settings = defaultSettings,]) => {
const options = setOptions(settings);
const { exists, id } = handleCache().listenerExists(type, listener, options);
var eventBus = function () {
var hubId = ' broadcast-node ';
var on = function (_a) {
var type = _a[0], listener = _a[1], _b = _a[2], settings = _b === void 0 ? defaultSettings : _b;
var options = setOptions(settings);
var _c = handleCache().listenerExists(type, listener, options), exists = _c.exists, id = _c.id;
if (exists && !options.allowDoublettesSubscribers) {

@@ -24,3 +39,3 @@ if (!options.useLatestSubscriberScope)

debugmode({
string: `Subscriber ${type} existed. Will update scope.`,
string: "Subscriber ".concat(type, " existed. Will update scope."),
obj: broadcastItemsCache,

@@ -30,8 +45,8 @@ });

debugmode({
string: `${exists ? `Updating listener scope for ${id}` : 'Setting new listener'} for "${type} (id:${id}})"`,
string: "".concat(exists ? "Updating listener scope for ".concat(id) : 'Setting new listener', " for \"").concat(type, " (id:").concat(id, "})\""),
obj: listener,
force: options.debug,
});
const eventTarget = createOrGetCustomEventNode(hubId);
const unbind = helpers().bind(eventTarget, {
var eventTarget = createOrGetCustomEventNode(hubId);
var unbind = helpers().bind(eventTarget, {
type: ('broadcast-' + type),

@@ -42,5 +57,6 @@ listener: listener,

};
const once = ([type, listener, settings = defaultSettings,]) => {
const options = setOptions(settings);
const { exists, id } = handleCache().listenerExists(type, listener, options);
var once = function (_a) {
var type = _a[0], listener = _a[1], _b = _a[2], settings = _b === void 0 ? defaultSettings : _b;
var options = setOptions(settings);
var _c = handleCache().listenerExists(type, listener, options), exists = _c.exists, id = _c.id;
if (exists && !options.allowDoublettesSubscribers)

@@ -50,8 +66,8 @@ return id;

debugmode({
string: `Setting "once" listener "${type}"`,
string: "Setting \"once\" listener \"".concat(type, "\""),
obj: listener,
force: true,
});
const eventTarget = createOrGetCustomEventNode(hubId);
const unbind = helpers().bind(eventTarget, {
var eventTarget = createOrGetCustomEventNode(hubId);
var unbind = helpers().bind(eventTarget, {
type: ('broadcast-' + type),

@@ -63,31 +79,32 @@ listener: listener,

};
const off = ([type, listener, settings = defaultSettings,]) => {
var _a;
if (typeof ((_a = listener) === null || _a === void 0 ? void 0 : _a.prototype) === 'undefined') {
var off = function (_a) {
var _b;
var type = _a[0], listener = _a[1], _c = _a[2], settings = _c === void 0 ? defaultSettings : _c;
if (typeof ((_b = listener) === null || _b === void 0 ? void 0 : _b.prototype) === 'undefined') {
throw new Error('Listener function not passed as a reference will not match previously set Broadcast listener.');
}
const options = setOptions(settings);
var options = setOptions(settings);
debugmode({
string: `Removing listener "${type}"`,
string: "Removing listener \"".concat(type, "\""),
obj: listener,
force: options.debug,
settings,
settings: settings,
});
handleCache().remove(type, listener);
const eventTarget = createOrGetCustomEventNode(hubId);
var eventTarget = createOrGetCustomEventNode(hubId);
eventTarget.removeEventListener('broadcast-' + type, listener);
};
const emit = (type, detail, settings) => {
var emit = function (type, detail, settings) {
debugmode({
string: `Emitted ${type}`,
string: "Emitted ".concat(type),
obj: detail,
force: settings === null || settings === void 0 ? void 0 : settings.debug,
});
const eventTarget = createOrGetCustomEventNode(hubId);
return eventTarget.dispatchEvent(new CustomEvent('broadcast-' + type, { detail }));
var eventTarget = createOrGetCustomEventNode(hubId);
return eventTarget.dispatchEvent(new CustomEvent('broadcast-' + type, { detail: detail }));
};
return { on, once, off, emit };
return { on: on, once: once, off: off, emit: emit };
// Initiate or retreive node for custom event.
function createOrGetCustomEventNode(hubId) {
const nodeIterator = document.createNodeIterator(document.body, NodeFilter.SHOW_COMMENT);
var nodeIterator = document.createNodeIterator(document.body, NodeFilter.SHOW_COMMENT);
while (nodeIterator.nextNode()) {

@@ -104,4 +121,4 @@ if (nodeIterator.referenceNode.nodeValue === hubId) {

function handleCache() {
const listenerExists = (type, listener, settings) => {
const id = createBroadcastId(type, listener);
var listenerExists = function (type, listener, settings) {
var id = createBroadcastId(type, listener);
debugmode({

@@ -114,25 +131,25 @@ string: 'broadcastItemsCache',

debugmode({
string: `Found a previous instans of ${type}.`,
string: "Found a previous instans of ".concat(type, "."),
force: settings.debug,
});
return { exists: true, id };
return { exists: true, id: id };
}
broadcastItemsCache.push(type + id);
return { exists: false, id };
return { exists: false, id: id };
};
const remove = (type, listener) => {
const removeId = type + createBroadcastId(type, listener);
var remove = function (type, listener) {
var removeId = type + createBroadcastId(type, listener);
debugmode({
string: `Remove listener: ${removeId}`,
string: "Remove listener: ".concat(removeId),
obj: broadcastItemsCache.indexOf(removeId) !== -1
? 'Existed'
: `Didn't exist`,
: "Didn't exist",
});
broadcastItemsCache = broadcastItemsCache.filter((id) => id !== removeId);
broadcastItemsCache = broadcastItemsCache.filter(function (id) { return id !== removeId; });
};
return { listenerExists, remove };
return { listenerExists: listenerExists, remove: remove };
}
// Serialize+hash the subscriber and store it to not add it twice.
function createBroadcastId(flag, details) {
let detailsStringified;
var detailsStringified;
switch (typeof details) {

@@ -147,3 +164,3 @@ case 'function':

catch (error) {
throw new Error(`Could not "JSON.stringify" the broadcasterjs payload of "${typeof details}" type.`);
throw new Error("Could not \"JSON.stringify\" the broadcasterjs payload of \"".concat(typeof details, "\" type."));
}

@@ -156,3 +173,3 @@ }

function setOptions(settings) {
const mergedOptions = Object.assign(Object.assign({}, defaultSettings), settings);
var mergedOptions = __assign(__assign({}, defaultSettings), settings);
if (mergedOptions.debugGlobal)

@@ -163,5 +180,10 @@ globalDebug = true;

function helpers() {
const hashCode = (s) => s.split('').reduce((a, b) => ((a << 5) - a + b.charCodeAt(0)) | 0, 0);
const serializeFn = (f, env) => JSON.stringify({ src: f.toString(), env: env });
const bind = (target, { type, listener, options, }) => {
var hashCode = function (s) {
return s.split('').reduce(function (a, b) { return ((a << 5) - a + b.charCodeAt(0)) | 0; }, 0);
};
var serializeFn = function (f, env) {
return JSON.stringify({ src: f.toString(), env: env });
};
var bind = function (target, _a) {
var type = _a.type, listener = _a.listener, options = _a.options;
target.addEventListener(type, listener, options);

@@ -172,13 +194,14 @@ return function unbind() {

};
return { serializeFn, hashCode, bind };
return { serializeFn: serializeFn, hashCode: hashCode, bind: bind };
}
function debugmode({ string, obj, force, settings, }) {
function debugmode(_a) {
var string = _a.string, obj = _a.obj, force = _a.force, settings = _a.settings;
if ((!globalDebug && !force) || (settings === null || settings === void 0 ? void 0 : settings.suppressDebug))
return;
const style = 'color:#bada55;background:#666;padding:0.3rem 0.5rem;border-radius:3px';
console.log(`%c${string}`, style, obj ? obj : '--');
var style = 'color:#bada55;background:#666;padding:0.3rem 0.5rem;border-radius:3px';
console.log("%c".concat(string), style, obj ? obj : '--');
}
};
const broadcast = eventBus();
export { broadcast };
var broadcast = eventBus();
exports.broadcast = broadcast;
// Usage

@@ -185,0 +208,0 @@ /*

{
"name": "@foundit/broadcasterjs",
"version": "1.1.1",
"version": "1.1.2",
"description": "A simple yet powerful pub/sub pattern javascript event bus",

@@ -5,0 +5,0 @@ "main": "dist/index.js",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc