Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'pubsub-js' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
/* global APP_STARTUP */
import PubSub from "pubsub-js";
import { debug, log, setAddonMetadata } from "./lib/utils";
import { startupDone, startupPromise, startupObserver } from "./lib/appStartup";
import { startupPrefsObserver, shutdownPrefsObserver } from "./lib/prefs";
import { startupFrameScripts, shutdownFrameScripts } from "./lib/frameScripts";
import { startupWebExtension, shutdownWebExtension } from "./lib/webExtension";
import { startupEvents, shutdownEvents } from "./lib/events";
import { startupChannels, shutdownChannels } from "./lib/channels";
import { startupTelemetry, shutdownTelemetry } from "./lib/telemetry";
import { startupAddonManager, shutdownAddonManager } from "./lib/addonManager";
PubSub.immediateExceptions = true;
export function startup(data, reason) {
setAddonMetadata(data);
if (reason === APP_STARTUP) {
startupObserver.register();
} else {
startupDone();
}
return startupPromise
.then(setupDebug)
.then(() => startupTelemetry(data, reason))
.then(startupAddonManager)
.then(startupPrefsObserver)
.then(startupEvents)
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* global browser */
import PubSub from "pubsub-js";
import { log, debug } from "./lib/utils";
import { setupStorage } from "./lib/storage";
import { setupEnvironment } from "./lib/environments";
import { setupBrowserAction } from "./lib/browserAction";
import { setupMetrics } from "./lib/metrics";
import { setupBootstrapPort, sendBootstrapMessage } from "./lib/bootstrap";
PubSub.immediateExceptions = true;
function setup() {
setupDebug()
.then(setupStorage)
.then(setupBrowserAction)
.then(setupMetrics)
.then(setupEnvironment)
.then(setupBootstrapPort)
.then(() => sendBootstrapMessage("ready"))
.catch(err => log("init error", err));
}
async function setupDebug() {
if (!debug) return;
["bootstrap", "webExtension"].forEach(root =>
PubSub.subscribe(root, (message, data) => log("pubsub", message, data))
};
var sessionPrestartConfirm_func = function (event_name, data) {
self.sessions[self.playerToSession[data['rand_user']]].sessionPrestartConfirm(data);
};
var sendFrame_func = function (event_name, data) {
self.sessions[self.playerToSession[data['rand_user']]].sendFrame(data);
};
var completedRound_func = function (event_name, data) {
self.sessions[self.playerToSession[data['rand_user']]].completedRound(data);
};
var terminateSession_func = function (event_name, data) {
console.log("Terminate Session: ", data['session_id']);
delete self.sessions[data['session_id']];
};
// sets the pubsub handlers for the dispatcher
this.readyForSession_pubsub = PubSub.subscribe('readyForSession', readyForSession_func);
this.readyPlayer_pubsub = PubSub.subscribe('playerReady', readyPlayer_func);
this.readyNotPlayer_pubsub = PubSub.subscribe('playerNotReady', readyNotPlayerr_func);
this.sessionPrestartConfirm_pubsub = PubSub.subscribe('sessionPrestartConfirm', sessionPrestartConfirm_func);
this.sendFrame_pubsub = PubSub.subscribe('sendFrame', sendFrame_func);
this.completedRound_pubsub = PubSub.subscribe('completedRound', completedRound_func);
this.exitSessionQuene_pubsub = PubSub.subscribe('exitSessionQuene', exitSessionQuene_func);
this.confirmedConnection_pubsub = PubSub.subscribe('confirmedSession', confirmed_connection_func);
this.leaveSession_pubsub = PubSub.subscribe('leaveSession', leaveSessionn_func);
this.disconnectUser_pubsub = PubSub.subscribe('disconnectUser', disconnectUser_func);
this.terminateSession_pubsub = PubSub.subscribe('terminateSession', terminateSession_func);
}
this.nextExecutionAddress = null
this.hasLoaded = false
this.inspectionAddress = null
this.cellSprite = null
this.nextExecutionSprite = null
this.sprites = []
this.state = {
height: 0,
width: 0
}
// oddly needs to happen here as unmount can happen AFTER a new instance has mounted :s
PubSub.unsubscribe('CORE_ACCESS')
PubSub.unsubscribe('RESET_CORE')
PubSub.unsubscribe('NEXT_EXECUTION')
PubSub.subscribe('CORE_ACCESS', (msg, data) => {
this.messages = this.messages.concat(data)
})
PubSub.subscribe('RESET_CORE', (msg, data) => {
this.messages = []
this.init()
})
PubSub.subscribe('NEXT_EXECUTION', (msg, data) => {
this.nextExecutionAddress = data.address
})
const eventEnd = event.seq.endMeasure;
const eventLength = isNaN( eventEnd ) ? 1 : eventEnd - eventStart;
event.seq.startMeasure = patternIndex;
event.seq.endMeasure = event.seq.startMeasure + eventLength;
}
});
});
}
Pubsub.publish( Messages.CREATE_LINKED_LISTS );
// update UI
Pubsub.publish( Messages.REFRESH_SONG );
Pubsub.publish( Messages.PATTERN_AMOUNT_UPDATED );
handleClose();
}
componentWillMount: function() {
var self = this;
// Setup all the subscriptions.
PubSub.subscribe(Editor.topics().ContentChange, self.handleContentChange);
PubSub.subscribe(MenuBar.topics().ModeChange, self.handleModeChange);
PubSub.subscribe(MenuBar.topics().ItemClick, self.handleMenuItemClick);
PubSub.subscribe(GitHub.topics().Token, self.handleGatekeeperToken);
PubSub.subscribe(Avatar.topics().LoginClick, self.handleLoginClick);
// If there's a gist id in the url, retrieve the gist.
var match = location.href.match(/[a-z\d]+$/);
if (match) {
GitHub.readGist(this.getToken(), match[0])
.then(function(gist) {
// Instruct Output to render all code.
self.makeOutputRenderAllCode.pop();
self.makeOutputRenderAllCode.push(true);
// Extract code contents and selected mode.
var data = GitHub.convertGistToLivecodingData(gist);
aEvent.preventDefault();
}
break;
case 83: // S
if ( hasOption ) {
Pubsub.publishSync( Messages.SAVE_SONG );
aEvent.preventDefault();
}
break;
case 86: // V
// paste current selection
if ( hasOption ) {
Pubsub.publishSync(
Messages.SAVE_STATE,
StateFactory.getAction( States.PASTE_SELECTION, {
efflux: efflux,
updateHandler: () => Pubsub.publishSync( Messages.REFRESH_PATTERN_VIEW )
})
);
}
break;
case 88: // X
// cut current selection
if ( hasOption )
{
Pubsub.publishSync(
function handleBroadcast( type, payload )
{
switch ( type )
{
case Messages.LOAD_SONG:
const song = ( typeof payload === "string" ) ? efflux.SongModel.getSongById( payload ) : payload;
if ( song && song.meta && song.patterns ) {
efflux.activeSong = ObjectUtil.clone( song );
efflux.EditorModel.reset();
efflux.EditorModel.amountOfSteps = song.patterns[ 0 ].steps;
SongUtil.resetPlayState( efflux.activeSong.patterns ); // ensures saved song hasn't got "frozen" events
Pubsub.publishSync( Messages.SONG_LOADED, song );
Pubsub.publishSync( Messages.CREATE_LINKED_LISTS );
efflux.StateModel.flush();
}
break;
case Messages.TRANSFORM_LEGACY_SONG:
if ( typeof payload === "object" )
SongValidator.transformLegacy( payload );
break;
case Messages.CREATE_LINKED_LISTS:
EventUtil.linkEvents( efflux.activeSong.patterns, efflux.eventList );
break;
case Messages.SAVE_STATE:
{
currentStep = 0;
// advance the measure if the Sequencer wasn't looping
if ( !looping && ++currentMeasure === totalMeasures )
{
// last measure reached, jump back to first
currentMeasure = 0;
// stop playing if we're recording and looping is disabled
if ( recording && !efflux.EditorModel.loopedRecording )
{
SequencerController.setPlaying( false );
Pubsub.publishSync( Messages.RECORDING_COMPLETE );
return;
}
}
SequencerController.setPosition( currentMeasure, nextNoteTime );
if ( recording )
{
// one bar metronome count in ?
if ( Metronome.countIn && !Metronome.countInComplete ) {
Metronome.enabled = Metronome.restore;
Metronome.countInComplete = true;
currentMeasure = 0; // now we're actually starting!
firstMeasureStartTime = audioContext.currentTime;
componentWillUnmount () {
// Unsubscribe from event once unmounting
PubSub.unsubscribe(this.subEvent)
this._isMounted = false
}