UNPKG

@pionjs/pion

Version:

Hooks for web components

45 lines (44 loc) 1.37 kB
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(disconnected) { if (typeof this._teardown === "function") { this._teardown(); // ensure effect is not torn down multiple times this._teardown = undefined; } // reset to pristine state when element is disconnected if (disconnected) { this.lastValues = this.values = undefined; } } hasChanged() { return (!this.lastValues || this.values.some((value, i) => this.lastValues[i] !== value)); } }); } export { createEffect };