Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'event-target-shim' 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.
'use strict';
import {NativeModules} from 'react-native';
import EventTarget from 'event-target-shim';
import getUserMedia from './getUserMedia';
const {WebRTCModule} = NativeModules;
const MEDIA_DEVICES_EVENTS = [
'devicechange'
];
class MediaDevices extends EventTarget(MEDIA_DEVICES_EVENTS) {
// TODO: implement.
ondevicechange: ?Function;
/**
* W3C "Media Capture and Streams" compatible {@code enumerateDevices}
* implementation.
*/
enumerateDevices() {
return new Promise(resolve => WebRTCModule.enumerateDevices(resolve));
}
/**
* W3C "Media Capture and Streams" compatible {@code getUserMedia}
* implementation.
* See: https://www.w3.org/TR/mediacapture-streams/#dom-mediadevices-enumeratedevices
*
'connecting' |
'open' |
'closing' |
'closed';
const DATA_CHANNEL_EVENTS = [
'open',
'message',
'bufferedamountlow',
'close',
'error',
];
class ResourceInUse extends Error {}
export default class RTCDataChannel extends EventTarget(DATA_CHANNEL_EVENTS) {
_peerConnectionId: number;
binaryType: 'arraybuffer' = 'arraybuffer'; // we only support 'arraybuffer'
bufferedAmount: number = 0;
bufferedAmountLowThreshold: number = 0;
id: number;
label: string;
maxPacketLifeTime: ?number = null;
maxRetransmits: ?number = null;
negotiated: boolean = false;
ordered: boolean = true;
protocol: string = '';
readyState: RTCDataChannelState = 'connecting';
onopen: ?Function;
'mute',
'unmute',
// see: https://www.w3.org/TR/mediacapture-streams/#constrainable-interface
'overconstrained',
];
type MediaStreamTrackState = "live" | "ended";
type SourceInfo = {
id: string;
label: string;
facing: string;
kind: string;
};
class MediaStreamTrack extends EventTarget(MEDIA_STREAM_TRACK_EVENTS) {
_enabled: boolean;
id: string;
kind: string;
label: string;
muted: boolean;
readonly: boolean; // how to decide?
// readyState in java: INITIALIZING, LIVE, ENDED, FAILED
readyState: MediaStreamTrackState;
remote: boolean;
onended: ?Function;
onmute: ?Function;
onunmute: ?Function;
overconstrained: ?Function;
constructor(info) {
'icecandidate',
'icecandidateerror',
'iceconnectionstatechange',
'icegatheringstatechange',
'negotiationneeded',
'signalingstatechange',
// Peer-to-peer Data API:
'datachannel',
// old:
'addstream',
'removestream',
];
let nextPeerConnectionId = 0;
export default class RTCPeerConnection extends EventTarget(PEER_CONNECTION_EVENTS) {
localDescription: RTCSessionDescription;
remoteDescription: RTCSessionDescription;
signalingState: RTCSignalingState = 'stable';
iceGatheringState: RTCIceGatheringState = 'new';
iceConnectionState: RTCIceConnectionState = 'new';
onconnectionstatechange: ?Function;
onicecandidate: ?Function;
onicecandidateerror: ?Function;
oniceconnectionstatechange: ?Function;
onicegatheringstatechange: ?Function;
onnegotiationneeded: ?Function;
onsignalingstatechange: ?Function;
onaddstream: ?Function;
}, [callback]);
// Set up the interval.
// eslint-disable-next-line
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
const id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
const evtTarget = new EventTarget();
const useStorage = (storage, keyPrefix) => (key, defaultValue) => {
const storeKey = `${keyPrefix}.${key}`;
const raw = storage.getItem(storeKey);
const [value, setValue] = useState(raw ? JSON.parse(raw) : defaultValue);
const updater = updatedValue => {
setValue(updatedValue);
storage.setItem(storeKey, JSON.stringify(updatedValue));
evtTarget.dispatchEvent(new CustomEvent('storage_change', { detail: { key } }));
};
if (defaultValue != null && !raw) {
updater(defaultValue);
}
useEffect(() => {
this.retries = params.retries || 5;
this.delayBeforeRetry = params.delayBeforeRetry || 5;
this.start = 0;
this.chunk = null;
this.chunkCount = 0;
this.totalChunks = Math.ceil(this.file.size / (this.chunkSize * 1000 * 1000));
this.retriesCount = 0;
this.offline = false;
this.paused = false;
this.headers['uploader-file-id'] = this._uniqid(this.file);
this.headers['uploader-chunks-total'] = this.totalChunks;
this._reader = new FileReader();
this._eventTarget = new EventTarget();
this._validateParams();
this._sendChunks();
// restart sync when back online
// trigger events when offline/back online
window.addEventListener('online', () => {
if (!this.offline) return;
this.offline = false;
this._eventTarget.dispatchEvent(new Event('online'));
this._sendChunks();
});
window.addEventListener('offline', () => {
this.offline = true;
* Sends a message to the reply channel.
*
* @param {Object} action The message
*
* @example
* Stream("myStream", ws).send({prop1: 'value1', prop2: 'value2'});
*/
send(action) {
const msg = {
stream: this.name,
payload: action,
};
this.socket.send(JSON.stringify(msg));
}
}
defineEventAttribute(Stream.prototype, "open");
defineEventAttribute(Stream.prototype, "close");
defineEventAttribute(Stream.prototype, "error");
defineEventAttribute(Stream.prototype, "message");
/**
* Bridge between Channels and plain javascript.
*
* @example
* const webSocketBridge = new WebSocketBridge();
* webSocketBridge.connect("http://example.com/ws/");
* webSocketBridge.addEventListener("message", function(event) {
* console.log(event.data);
* });
*/
export class WebSocketBridge extends Forwarder {
constructor(options) {
* @param {Object} action The message
*
* @example
* Stream("myStream", ws).send({prop1: 'value1', prop2: 'value2'});
*/
send(action) {
const msg = {
stream: this.name,
payload: action,
};
this.socket.send(JSON.stringify(msg));
}
}
defineEventAttribute(Stream.prototype, "open");
defineEventAttribute(Stream.prototype, "close");
defineEventAttribute(Stream.prototype, "error");
defineEventAttribute(Stream.prototype, "message");
/**
* Bridge between Channels and plain javascript.
*
* @example
* const webSocketBridge = new WebSocketBridge();
* webSocketBridge.connect("http://example.com/ws/");
* webSocketBridge.addEventListener("message", function(event) {
* console.log(event.data);
* });
*/
export class WebSocketBridge extends Forwarder {
constructor(options) {
super();
this.socket = null;
this.dispatchEvent(event)
}
private handleWebsocketInfo = ({
id,
info
}: IClientTopics['websocketInfo']) => {
if (id !== this.id) return
Object.keys(info).forEach(key => (this[key] = info[key]))
}
}
defineEventAttribute(WebSocket.prototype, 'close')
defineEventAttribute(WebSocket.prototype, 'error')
defineEventAttribute(WebSocket.prototype, 'message')
defineEventAttribute(WebSocket.prototype, 'open')
this.dispatchEvent(event)
}
private handleWebsocketInfo = ({
id,
info
}: IClientTopics['websocketInfo']) => {
if (id !== this.id) return
Object.keys(info).forEach(key => (this[key] = info[key]))
}
}
defineEventAttribute(WebSocket.prototype, 'close')
defineEventAttribute(WebSocket.prototype, 'error')
defineEventAttribute(WebSocket.prototype, 'message')
defineEventAttribute(WebSocket.prototype, 'open')