sys-global
v1.0.5
Published
SysGlobal is a global state and event management library that provides a simple API to manage global state and event in a single instance.
Downloads
404
Readme
SysGlobal Usage
SysGlobal is a global state and event management library that provides a simple API to manage global state and event in a single instance.
Installation
To install SysGlobal
, use npm or yarn or pnpm:
npm install sys-global
or
yarn add sys-global
or
pnpm add sys-global
To use SysGlobal
in a browser, include the following script tag in your HTML file:
<script src="dist/sys.global.js"></script>
<script>
const SysGlobal = __sys_global_module__.default;
window.SYSGLOBAL = SysGlobal.init(window, 'SYSGLOBAL');
</script>
API
SysGlobal class
SysGlobal.init(window, name)
Initializes the global state with the given name.
SysGlobal instance
sysGlobal.createStore(name, config)
Creates a new store with the specified name and configuration.
sysGlobal.store.<name>
Gets the store with the specified name.
sysGlobal.get(stores, [selector], [defaultValue])
Gets the value of the store using the selector.
sysGlobal.createEmitter(name)
Creates a new emitter with the specified name.
sysGlobal.emitter.<name>.on(event, callback)
Registers an event listener for the specified event.
sysGlobal.emitter.<name>.emit(event)
Emits the specified event.
Examples
Store Example
import SysGlobal from 'sys-global';
// Initialize the global state in a single instance
window.SYSGLOBAL = SysGlobal.init(window, 'SYSGLOBAL');
// Create a new store (zustand vanilla under the hood)
window.SYSGLOBAL.createStore('counter', (set) => ({
count: 0,
incr: () => set((state) => ({ count: state.count + 1 })),
decr: () => set((state) => ({ count: state.count - 1 })),
}));
// Use the store directly
const { count, incr, decr } = window.SYSGLOBAL.store.counter.getState();
// Use get helper(recommanded)
window.SYSGLOBAL.get('counter', s => s.count);
window.SYSGLOBAL.get(window.SYSGLOBAL?.store?.counter, s => s.count);
// Use zustand hook in React
import { useStore } from 'zustand';
const { count, incr, decr } = useStore(window.SYSGLOBAL.store.counter);
// Use our custom hook store with default value in React (recommended)
import { useStoreWithDefault } from 'sys-global/react';
const count = useStoreWithDefault(window.SYSGLOBAL?.store?.counter, s => s.count, 10);
Emitter Example
// An internal emitter for store
window.SYSGLOBAL.emitter.store.on('create', (name) => {
console.log(`store ${name} created`);
});
// Custom emitter
window.SYSGLOBAL.createEmitter('user');
window.SYSGLOBAL.emitter.user.on('create', () => {
console.log('user created');
});
window.SYSGLOBAL.emitter.user.emit('create');
License
This project is licensed under the MIT License.