misuzu/assets/misuzu.js/watcher.js

66 lines
1.6 KiB
JavaScript
Raw Permalink Normal View History

2023-01-29 01:51:54 +00:00
const MszWatcher = function() {
2024-01-24 21:53:26 +00:00
const handlers = [];
2023-01-29 01:51:54 +00:00
2024-01-24 21:53:26 +00:00
const watch = (handler, ...args) => {
if(typeof handler !== 'function')
throw 'handler must be a function';
if(handlers.includes(handler))
throw 'handler already registered';
2023-01-29 01:51:54 +00:00
2024-01-24 21:53:26 +00:00
handlers.push(handler);
args.push(true);
handler(...args);
};
2023-01-29 01:51:54 +00:00
2024-01-24 21:53:26 +00:00
const unwatch = handler => {
$ari(handlers, handler);
};
2023-01-29 01:51:54 +00:00
2024-01-24 21:53:26 +00:00
return {
watch: watch,
unwatch: unwatch,
call: (...args) => {
2023-01-29 01:51:54 +00:00
args.push(false);
2024-01-24 21:53:26 +00:00
for(const handler of handlers)
handler(...args);
2023-01-29 01:51:54 +00:00
},
};
};
2024-01-30 23:47:02 +00:00
const MszWatchers = function() {
2024-01-24 21:53:26 +00:00
const watchers = new Map;
2023-01-29 01:51:54 +00:00
2024-01-24 21:53:26 +00:00
const getWatcher = name => {
const watcher = watchers.get(name);
if(watcher === undefined)
2023-01-29 01:51:54 +00:00
throw 'undefined watcher name';
2024-01-24 21:53:26 +00:00
return watcher;
2023-01-29 01:51:54 +00:00
};
2024-01-24 21:53:26 +00:00
const watch = (name, handler, ...args) => {
getWatcher(name).watch(handler, ...args);
};
const unwatch = (name, handler) => {
getWatcher(name).unwatch(handler);
2023-01-29 01:51:54 +00:00
};
return {
watch: watch,
unwatch: unwatch,
2024-01-24 21:53:26 +00:00
define: names => {
if(typeof names === 'string')
watchers.set(names, new MszWatcher);
else if(Array.isArray(names))
for(const name of names)
watchers.set(name, new MszWatcher);
else
throw 'names must be an array of names or a single name';
},
call: (name, ...args) => {
getWatcher(name).call(...args);
2023-01-29 01:51:54 +00:00
},
};
};