convex-pixel
Version:
The library for creating pseudo 3d interactive scenes based on webgl
64 lines • 2.03 kB
JavaScript
import * as PIXI from "pixi.js";
import { SonarEventTypes, Sonar } from "./sonar";
export class SonarDetector extends PIXI.utils.EventEmitter {
constructor(_object, _detectedProps, _eventType = SonarEventTypes.CHANGE) {
super();
this._object = _object;
this._detectedProps = _detectedProps;
this._eventType = _eventType;
this._snapshot = {};
this._detectChangesHandler = (nextStep = false) => {
this.detectChanges(nextStep);
};
this.startDetection();
}
detectChanges(nextStep = false) {
if (nextStep) {
this._detectChangesNextFrame();
return;
}
if (!this._object) {
this.emit(SonarEventTypes.LOST_CONTEXT);
return;
}
if (!this.detectedProps) {
throw Error(`Property "detectedProps" is not defined.`);
}
for (const prop of this.detectedProps) {
const current = this._object;
const previous = this._snapshot;
if (current[prop] !== previous[prop]) {
previous[prop] = current[prop];
this.emit(this._eventType);
break;
}
}
}
destroy() {
this.stopDetection();
this.removeAllListeners();
this._object = undefined;
this._snapshot = undefined;
this._detectedProps = undefined;
}
startDetection() {
Sonar.instance.add(this);
}
stopDetection() {
clearTimeout(this._nextTimeoutId);
if (Sonar.instance) {
Sonar.instance.remove(this);
}
}
get detectedProps() {
return this._detectedProps;
}
get eventType() {
return this._eventType;
}
_detectChangesNextFrame() {
clearTimeout(this._nextTimeoutId);
this._nextTimeoutId = setTimeout(this._detectChangesHandler, 0);
}
}
//# sourceMappingURL=sonar-detector.js.map