Package Exports
- life-cycle-hooks
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (life-cycle-hooks) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
life-cycle-hooks
A clean way to bind functions to events in custom code
Install
npm i --save life-cycle-hooks
Usage
Start by initializing a lifecycle object:
const LifeCycle = require('./lifecycle.js');
const lifecycle = new LifeCycle();
Then, to attach events:
lifecycle.on('some_event', (args, sent, by, event) => {
console.log("some event happened")
})
To trigger all events bound to 'some_event':
lifecycle.trigger('some_event', "args", "to", "the", "bound", "function")
Example use case
Suppose you have a websocket server, and you want to respond differently for mobile and desktop:
ws_server.on('connection', async function connection(ws, req) {
if(isMobile(req)) {
lifecycle.trigger('mobile_connection', ws);
} else {
lifecycle.trigger('desktop_connection', ws);
}
}
You can then return lifecycle
, and in another part of your code, do the following:
lifecycle.on('mobile_connection', (ws) => {
ws.send('hello mobile user');
});
lifecycle.on('desktop_connection', (ws) => {
ws.send('hello desktop user');
});