@foundit/broadcasterjs
Advanced tools
Comparing version 1.0.5 to 1.1.0
@@ -1,20 +0,6 @@ | ||
"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; | ||
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()) === | ||
let broadcastItemsCache = []; | ||
let globalDebug = ((_a = new URLSearchParams(window.location.search).get('debug')) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === | ||
'broadcasterjs'; | ||
var defaultSettings = { | ||
const defaultSettings = { | ||
debug: false, | ||
@@ -26,15 +12,14 @@ debugGlobal: false, | ||
}; | ||
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; | ||
const eventBus = () => { | ||
const hubId = ' broadcast-node '; | ||
const on = ([type, listener, settings = defaultSettings,]) => { | ||
const options = setOptions(settings); | ||
const { exists, id } = handleCache().listenerExists(type, listener, options); | ||
if (exists && !options.allowDoublettesSubscribers) { | ||
if (!options.useLatestSubscriberScope) | ||
return id; | ||
return null; | ||
// Remove previous listener and set new to update scope. | ||
off([type, listener, { suppressDebug: true }]); | ||
debugmode({ | ||
string: "Subscriber ".concat(type, " existed. Will update scope."), | ||
string: `Subscriber ${type} existed. Will update scope.`, | ||
obj: broadcastItemsCache, | ||
@@ -44,14 +29,16 @@ }); | ||
debugmode({ | ||
string: "".concat(exists ? "Updating listener scope for ".concat(id) : 'Setting new listener', " for \"").concat(type, " (id:").concat(id, "})\""), | ||
string: `${exists ? `Updating listener scope for ${id}` : 'Setting new listener'} for "${type} (id:${id}})"`, | ||
obj: listener, | ||
force: options.debug, | ||
}); | ||
var eventTarget = createOrGetCustomEventNode(hubId); | ||
eventTarget.addEventListener('broadcast-' + type, listener); | ||
return id; | ||
const eventTarget = createOrGetCustomEventNode(hubId); | ||
const unbind = helpers().bind(eventTarget, { | ||
type: ('broadcast-' + type), | ||
listener: listener, | ||
}); | ||
return unbind; | ||
}; | ||
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; | ||
const once = ([type, listener, settings = defaultSettings,]) => { | ||
const options = setOptions(settings); | ||
const { exists, id } = handleCache().listenerExists(type, listener, options); | ||
if (exists && !options.allowDoublettesSubscribers) | ||
@@ -61,36 +48,43 @@ return id; | ||
debugmode({ | ||
string: "Setting \"once\" listener \"".concat(type, "\""), | ||
string: `Setting "once" listener "${type}"`, | ||
obj: listener, | ||
force: true, | ||
}); | ||
var eventTarget = createOrGetCustomEventNode(hubId); | ||
eventTarget.addEventListener('broadcast-' + type, listener, { once: true }); | ||
return id; | ||
const eventTarget = createOrGetCustomEventNode(hubId); | ||
const 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 options = setOptions(settings); | ||
const off = ([type, listener, settings = defaultSettings,]) => { | ||
var _a; | ||
if (typeof ((_a = listener) === null || _a === void 0 ? void 0 : _a.prototype) === 'undefined') { | ||
throw new Error('Listener function not passed as a reference will not match previously set Broadcast listener.'); | ||
} | ||
const options = setOptions(settings); | ||
debugmode({ | ||
string: "Removing listener \"".concat(type, "\""), | ||
string: `Removing listener "${type}"`, | ||
obj: listener, | ||
force: options.debug, | ||
settings: settings, | ||
settings, | ||
}); | ||
handleCache().remove(type, listener); | ||
var eventTarget = createOrGetCustomEventNode(hubId); | ||
const eventTarget = createOrGetCustomEventNode(hubId); | ||
eventTarget.removeEventListener('broadcast-' + type, listener); | ||
}; | ||
var emit = function (type, detail, settings) { | ||
const emit = (type, detail, settings) => { | ||
debugmode({ | ||
string: "Emitted ".concat(type), | ||
string: `Emitted ${type}`, | ||
obj: detail, | ||
force: settings === null || settings === void 0 ? void 0 : settings.debug, | ||
}); | ||
var eventTarget = createOrGetCustomEventNode(hubId); | ||
return eventTarget.dispatchEvent(new CustomEvent('broadcast-' + type, { detail: detail })); | ||
const eventTarget = createOrGetCustomEventNode(hubId); | ||
return eventTarget.dispatchEvent(new CustomEvent('broadcast-' + type, { detail })); | ||
}; | ||
return { on: on, once: once, off: off, emit: emit }; | ||
return { on, once, off, emit }; | ||
// Initiate or retreive node for custom event. | ||
function createOrGetCustomEventNode(hubId) { | ||
var nodeIterator = document.createNodeIterator(document.body, NodeFilter.SHOW_COMMENT); | ||
const nodeIterator = document.createNodeIterator(document.body, NodeFilter.SHOW_COMMENT); | ||
while (nodeIterator.nextNode()) { | ||
@@ -107,4 +101,4 @@ if (nodeIterator.referenceNode.nodeValue === hubId) { | ||
function handleCache() { | ||
var listenerExists = function (type, listener, settings) { | ||
var id = createBroadcastId(type, listener); | ||
const listenerExists = (type, listener, settings) => { | ||
const id = createBroadcastId(type, listener); | ||
debugmode({ | ||
@@ -117,25 +111,25 @@ string: 'broadcastItemsCache', | ||
debugmode({ | ||
string: "Found a previous instans of ".concat(type, "."), | ||
string: `Found a previous instans of ${type}.`, | ||
force: settings.debug, | ||
}); | ||
return { exists: true, id: id }; | ||
return { exists: true, id }; | ||
} | ||
broadcastItemsCache.push(type + id); | ||
return { exists: false, id: id }; | ||
return { exists: false, id }; | ||
}; | ||
var remove = function (type, listener) { | ||
var removeId = type + createBroadcastId(type, listener); | ||
const remove = (type, listener) => { | ||
const removeId = type + createBroadcastId(type, listener); | ||
debugmode({ | ||
string: "Remove listener: ".concat(removeId), | ||
string: `Remove listener: ${removeId}`, | ||
obj: broadcastItemsCache.indexOf(removeId) !== -1 | ||
? 'Existed' | ||
: "Didn't exist", | ||
: `Didn't exist`, | ||
}); | ||
broadcastItemsCache = broadcastItemsCache.filter(function (id) { return id !== removeId; }); | ||
broadcastItemsCache = broadcastItemsCache.filter((id) => id !== removeId); | ||
}; | ||
return { listenerExists: listenerExists, remove: remove }; | ||
return { listenerExists, remove }; | ||
} | ||
// Serialize+hash the subscriber and store it to not add it twice. | ||
function createBroadcastId(flag, details) { | ||
var detailsStringified; | ||
let detailsStringified; | ||
switch (typeof details) { | ||
@@ -150,3 +144,3 @@ case 'function': | ||
catch (error) { | ||
throw new Error("Could not \"JSON.stringify\" the broadcasterjs payload of \"".concat(typeof details, "\" type.")); | ||
throw new Error(`Could not "JSON.stringify" the broadcasterjs payload of "${typeof details}" type.`); | ||
} | ||
@@ -159,3 +153,3 @@ } | ||
function setOptions(settings) { | ||
var mergedOptions = __assign(__assign({}, defaultSettings), settings); | ||
const mergedOptions = Object.assign(Object.assign({}, defaultSettings), settings); | ||
if (mergedOptions.debugGlobal) | ||
@@ -166,20 +160,21 @@ globalDebug = true; | ||
function helpers() { | ||
var hashCode = function (s) { | ||
return s.split('').reduce(function (a, b) { return ((a << 5) - a + b.charCodeAt(0)) | 0; }, 0); | ||
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, }) => { | ||
target.addEventListener(type, listener, options); | ||
return function unbind() { | ||
target.removeEventListener(type, listener, options); | ||
}; | ||
}; | ||
var serializeFn = function (f, env) { | ||
return JSON.stringify({ src: f.toString(), env: env }); | ||
}; | ||
return { serializeFn: serializeFn, hashCode: hashCode }; | ||
return { serializeFn, hashCode, bind }; | ||
} | ||
function debugmode(_a) { | ||
var string = _a.string, obj = _a.obj, force = _a.force, settings = _a.settings; | ||
function debugmode({ string, obj, force, settings, }) { | ||
if ((!globalDebug && !force) || (settings === null || settings === void 0 ? void 0 : settings.suppressDebug)) | ||
return; | ||
var style = 'color:#bada55;background:#666;padding:0.3rem 0.5rem;border-radius:3px'; | ||
console.log("%c".concat(string), style, obj ? obj : '--'); | ||
const style = 'color:#bada55;background:#666;padding:0.3rem 0.5rem;border-radius:3px'; | ||
console.log(`%c${string}`, style, obj ? obj : '--'); | ||
} | ||
}; | ||
var broadcast = eventBus(); | ||
exports.broadcast = broadcast; | ||
const broadcast = eventBus(); | ||
export { broadcast }; | ||
// Usage | ||
@@ -190,11 +185,13 @@ /* | ||
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 + ' '); | ||
@@ -204,7 +201,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') | ||
@@ -219,3 +214,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. | ||
@@ -226,5 +221,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. | ||
*/ |
{ | ||
"name": "@foundit/broadcasterjs", | ||
"version": "1.0.5", | ||
"version": "1.1.0", | ||
"description": "A simple yet powerful pub/sub javascript event bus", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.js", |
@@ -26,8 +26,8 @@ # broadcasterjs | ||
useEffect(() => { | ||
broadcast.on(['MYBROADCAST-ID', myFlagEmittedCallbackFunction]) | ||
return () => broadcast.off(['MYBROADCAST-ID', myFlagEmittedCallbackFunction]) | ||
const off = broadcast.on(['MYBROADCAST-ID', myFlagEmittedCallbackFunction]) | ||
return off // optional | ||
}, [myFlagEmittedCallbackFunction]) | ||
``` | ||
The return function is optional, BroadcasterJS is managing this anyway but React migth warn about memory leaks never the less. | ||
The return function is optional, BroadcasterJS is managing this anyway but React migth warn about memory leaks never the less if you don't include it. | ||
@@ -37,3 +37,3 @@ ##### START SUBSCRIPTION VANILLA JS | ||
```typescript | ||
broacast.on([ | ||
const off() = broadcast.on([ | ||
'MYBROADCAST-ID', | ||
@@ -47,3 +47,3 @@ ({ detail }) => { | ||
```typescript | ||
broacast.once([ | ||
const off() = broadcast.once([ | ||
'MYBROADCAST-ID', | ||
@@ -59,8 +59,3 @@ ({ detail }) => { | ||
```typescript | ||
broacast.off([ | ||
'MYBROADCAST-ID', | ||
({ detail }) => { | ||
document.body.append(detail + ' ') | ||
}, | ||
]) | ||
off() // Use the subscribers return function. | ||
``` | ||
@@ -86,3 +81,3 @@ | ||
The broadcaster functions `on`,`once`,`off` takes an optional third value and `emit` takes an optional third argument in the form of a settings object. | ||
The broadcaster functions `on`,`once` takes an optional third value and `emit` takes an optional third argument in the form of a settings object. | ||
@@ -99,2 +94,12 @@ ```typescript | ||
Broadcasterjs does prevent doublettes with the same subscriber combination (flag + callback function). If you for some reason would want the same combination on another place in the code either just add a minor change, a comment in the callback function etc or send in the settings object with `allowDoublettesSubscribers` set to true. | ||
--- | ||
##### Change log | ||
**v 1.1.0** The subscribe functions 'on' and 'once' now return a unsubscribe function (no arguments) that is much more user friendly than the previous off function. 'off' is still available but removed from the documentation. | ||
##### Commands | ||
Publish to npm: `npm publish --access=public` | ||
Compile typescript: `tsc` | ||
Develop: `yarn start` |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
100
22778
436