lincd
Version:
LINCD is a JavaScript library for building user interfaces with linked data (also known as 'structured data', or RDF)
94 lines • 3.38 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.eventBatcher = exports.EventBatcher = void 0;
/*
* 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 https://mozilla.org/MPL/2.0/.
*/
const nextTick = require("next-tick");
const eventemitter3_1 = require("eventemitter3");
const CoreSet_1 = require("../collections/CoreSet");
class EventBatcher extends eventemitter3_1.EventEmitter {
constructor() {
super(...arguments);
this.batching = false;
this.emitters = new CoreSet_1.CoreSet();
}
hasBatchedEvents(filterFn) {
if (filterFn && this.batching) {
return this.emitters.filter(filterFn).size > 0;
}
return this.batching;
}
getPendingEmitters(filterFn) {
if (filterFn && this.batching) {
return this.emitters.filter(filterFn);
}
return this.emitters;
}
promiseDone() {
if (this.emitters.size == 0) {
return Promise.resolve(true);
}
else {
return new Promise((resolve, reject) => {
this.once(EventBatcher.ALL_EVENTS_DISPATCHED, () => {
resolve(true);
});
});
}
}
dispatchBatchedEventsOnceReady() {
//if we're currently emitting events, then we dont want to do nextTick yet, because those who consume events may want to set nextTick first
if (this.emitting) {
//so once all is dispatched, then we dispatch again
this.once(EventBatcher.ALL_EVENTS_DISPATCHED, () => {
nextTick(this.dispatchBatchedEvents.bind(this));
});
}
else {
//we're already not emitting, so on the next tick we can dispatch events
nextTick(this.dispatchBatchedEvents.bind(this));
}
}
dispatchBatchedEvents() {
//reset things before emitting so that new events will be added to new stacks
var toEmit = this.emitters;
this.emitters = new CoreSet_1.CoreSet();
this.batching = false;
this.emitting = true;
//tell all emitters to dispatch
toEmit.forEach((emitter) => {
emitter.emitBatchedEvents();
});
this.emitting = false;
this.emit(EventBatcher.ALL_EVENTS_DISPATCHED);
}
dispatchSomeEvents(filterEmitters) {
//tell all emitters to dispatch
this.emitters.forEach((emitter) => {
if (filterEmitters(emitter)) {
emitter.emitBatchedEvents();
this.emitters.delete(emitter);
}
});
this.batching = this.emitters.size > 0;
return this.batching;
}
get isBatching() {
return this.batching;
}
register(emitter) {
//first time someone registers an event we will make sure to emit all batched events at the next tick
if (!this.batching) {
this.batching = true;
this.dispatchBatchedEventsOnceReady();
}
this.emitters.add(emitter);
}
}
exports.EventBatcher = EventBatcher;
EventBatcher.ALL_EVENTS_DISPATCHED = 'ALL_EVENTS_DISPATCHED';
exports.eventBatcher = new EventBatcher();
//# sourceMappingURL=EventBatcher.js.map