We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
inspired by:
Usage:
/** * @typedef { Object } modelChanges * @property { String } prop * @property { * } oldValue * @property { * } newValue */ const observer = new ReactiveModelObserver(function(changes){ /** * @type { modelChanges } changes */ console.log("something get changes:", changes); }); const model = {}; observer.observe(model);
Implement:
class ReactiveModelObserver { constructor(reactiveCallback) { this.callback = reactiveCallback; this.storeModel = {}; this.target = null; } observe(target = {}) { this.target = target; Object.keys(target).forEach((prop) => { this.storeModel[prop] = target[prop]; Object.defineProperty(target, prop, { configurable: true, enumerable: true, get: () => this.storeModel[prop], set: (val) => { let oldValue = this.storeModel[prop]; this.storeModel[prop] = val; this._notify({ prop: prop, oldValue: oldValue, newValue: val }); } }); }); } disconnect() { const { target } = this; Object.keys(target).forEach((prop) => { Object.defineProperty(target, prop, { value: this.storeModel[prop], configurable: true, enumerable: true, writable: true }); }); this.target = null; this.storeModel = null; return this; } _notify(mutation) { this._attemptExec(this.callback, [mutation]); } _attemptExec(fn, args, context) { if ("function" !== typeof fn) { return } return fn.apply(context, args); } }
The text was updated successfully, but these errors were encountered:
Usage Example:
const observer = new ReactiveModelObserver(function(changes){ console.log("something get changes:", changes); }); const model = { name: "lily", age: 18, weight: "50kg" }; observer.observe(model); model.name = "lucy" model.age = 20; model.weight = "44kg"; console.log(`model: ${model.name} ${model.age} ${model.weight}`); setTimeout(() => { console.log("unload reactive model:"); console.log(`model: ${model.name} ${model.age} ${model.weight}`); observer.disconnect(); model.weight = "42kg"; console.log(`model: ${model.name} ${model.age} ${model.weight}`); console.log("nothing changes should fire") }, 1e3);
Sorry, something went wrong.
No branches or pull requests
inspired by:
Usage:
Implement:
The text was updated successfully, but these errors were encountered: