Skip to content

Commit

Permalink
docs: explain usage of listen/emit.
Browse files Browse the repository at this point in the history
  • Loading branch information
crhallberg committed Mar 13, 2024
1 parent a5d3a73 commit f8fe5f6
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions themes/bootstrap3/js/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,23 +30,34 @@ var VuFind = (function VuFind() {
}
}

// Add a function to call when an event is emitted
//
// Options:
// - once: remove this listener after it's been called
function listen(event, fn, { once = false } = {}) {
if (typeof listeners[event] === "undefined") {
listeners[event] = [];
}

listeners[event].push(fn);
const removeListener = () => unlisten(event, fn);

if (once) {
listeners[event].push(() => {
unlisten(event, fn);
});
// Remove a "once" listener after calling
// Add the function to remove the listener
// to the array, listeners are called in order
listeners[event].push(removeListener);
}

return () => unlisten(event, fn);
// Return a function to disable the listener
// Makes it easier to control activating and deactivating listeners
// This is common for similar libraries
return removeListener;
}

// Broadcat an event, passing arguments to all listeners
function emit(event, ...args) {
// No listeners for this event
if (typeof listeners[event] === "undefined") {
return;
}
Expand Down

0 comments on commit f8fe5f6

Please sign in to comment.