haunted
Version:
Hooks for web components
39 lines (38 loc) • 1.08 kB
JavaScript
import { Hook, hook } from "./hook";
function createEffect(setEffects) {
return hook(class extends Hook {
callback;
lastValues;
values;
_teardown;
constructor(id, state, ignored1, ignored2) {
super(id, state);
setEffects(state, this);
}
update(callback, values) {
this.callback = callback;
this.values = values;
}
call() {
const hasChanged = !this.values || this.hasChanged();
this.lastValues = this.values;
if (hasChanged) {
this.run();
}
}
run() {
this.teardown();
this._teardown = this.callback.call(this.state);
}
teardown() {
if (typeof this._teardown === "function") {
this._teardown();
}
}
hasChanged() {
return (!this.lastValues ||
this.values.some((value, i) => this.lastValues[i] !== value));
}
});
}
export { createEffect };