hd-utils
Version:
A handy utils for modern JS developers
40 lines (35 loc) • 1.12 kB
JavaScript
/**
* @description will call the passed object whenever the returned object is changed and will pass the prev and the current object.target.
* @example const watcher = createWatcher({ name: 'John', age: 25 });
// Observer function
const callbackFunction: ChangeCallback<{ name: string; age: number }> = (prev, current) => {
console.log('Object changed:', prev, '->', current);
};
// Start observing
watcher.observe(callbackFunction);
// Trigger changes
watcher.target.name = 'Alice';
watcher.target.age = 30;
// Stop observing
watcher.unobserve(callbackFunction);
*/
export default function createWatchers(target) {
const callbacks = [];
const proxy = new Proxy(target, {
set: (obj, prop, value) => {
const prevValue = { ...obj };
obj[prop] = value;
callbacks.forEach((callback) => callback(prevValue, { ...obj }));
return true;
},
});
return {
target: proxy,
observe: (callback) => {
callbacks.push(callback);
},
unobserve: () => {
callbacks.length = 0;
},
};
}