1
0
mirror of https://github.com/tobspr/shapez.io.git synced 2024-10-27 20:34:29 +00:00
tobspr_shapez.io/src/js/core/tracked_state.js
2020-05-09 16:45:23 +02:00

40 lines
1.1 KiB
JavaScript

export class TrackedState {
constructor(callbackMethod = null, callbackScope = null) {
this.lastSeenValue = null;
if (callbackMethod) {
this.callback = callbackMethod;
if (callbackScope) {
this.callback = this.callback.bind(callbackScope);
}
}
}
set(value, changeHandler = null, changeScope = null) {
if (value !== this.lastSeenValue) {
// Copy value since the changeHandler call could actually modify our lastSeenValue
const valueCopy = value;
this.lastSeenValue = value;
if (changeHandler) {
if (changeScope) {
changeHandler.call(changeScope, valueCopy);
} else {
changeHandler(valueCopy);
}
} else if (this.callback) {
this.callback(value);
} else {
assert(false, "No callback specified");
}
}
}
setSilent(value) {
this.lastSeenValue = value;
}
get() {
return this.lastSeenValue;
}
}