Hooks JS
Install with NPM:
npm i @mollahdev/hooks-js
A simple and efficient event manager for JavaScript.
This package assumes that your code will run in an ES2015+ environment.
API Usage
- addAction( 'hookName', callback, priority )
- doAction( 'hookName', data )
- removeAction( 'hookName', callback )
- addFilter( 'hookName', callback, priority )
- applyFilters( 'hookName', data )
- removeFilter( 'hookName', callback )
addAction Hook
addAction is the hook that the hooks-js execute when you call the doAction. The callback function of addAction expect some data that will be passed from doAction. The data can be optional.
import { addAction } from '@mollahdev/hooks-js';
import hooks from '@mollahdev/hooks-js';
const callback = function (data) {
};
addAction('core/ready', callback);
hooks.addAction('core/ready', callback, 50);
doAction Hook
doAction is the hook that the hooks-js use to run all the addActions you used in your application. You can pass any typeof of data you want.
import { doAction } from '@mollahdev/hooks-js';
import hooks from '@mollahdev/hooks-js';
doAction('core/ready', { user: 'Jhone Doe' });
hooks.doAction('core/ready');
addFilter Hook
addFilter hook allows you to modify the data that has been passed through applyFilters hook. addFilter hooks should be declared before applyFilters. The callback of addFilter receives the data used in applyFilters, the callback must return the data, You can modify the data before returning.
import { addFilter } from '@mollahdev/hooks-js';
import hooks from '@mollahdev/hooks-js';
const callback = (user) => {
user.hasAccess = false;
return user;
};
addFilter('namespace/current-user', callback);
hooks.addFilter('namespace.user', callback, 90);
applyFilters Hook
This hook invokes all the callback attached to addFilter hook. From the addFilter hook you can modify the data passing throw applyFilters.
import { applyFilters } from '@mollahdev/hooks-js';
import hooks from '@mollahdev/hooks-js';
const user = applyFilters('namespace/current-user', {
_id: 'something',
name: 'Jhone Doe',
});
console.log(user);
const anotherUser = hooks.applyFilters('namespace.user', {
role: 'editor',
});
console.log(anotherUser);
removeAction/removeFilter Hook
Remove any added addAction/addFilter with given hook name and same callback
import { removeAction, removeFilter } from '@mollahdev/hooks-js';
import hooks from '@mollahdev/hooks-js';
removeAction('your-hook-name', callback);
removeFilter('your-hook-name', callback);
hooks.removeAction('core/hook-name', callback);
hooks.removeFilter('core/hook-name', callback);