JavaScript hook system.
const {hook} = require('@taufik-nurrohman/hook');
hook(window);
window.on('click', () => console.log('click 1'));
window.on('click', () => console.log('click 2'));
window.on('focus', () => console.log('focus 1'));
console.log(window.hooks);
import {hook} from '@taufik-nurrohman/hook';
hook(window);
window.on('click', () => console.log('click 1'));
window.on('click', () => console.log('click 2'));
window.on('focus', () => console.log('focus 1'));
console.log(window.hooks);
Create hook properties to an object.
hook(window);
window.addEventListener('resize', () => {
window.fire('window-resize', [{
height: window.innerHeight,
width: window.innerWidth
}]);
});
Fire a hook.
window.addEventListener('resize', () => {
window.fire('window-resize', [{
height: window.innerHeight,
width: window.innerWidth
}]);
});
window.on('test', function (a, b, c) {
console.log(this); // Returns `Set [1, 2, 3]`
console.log({a, b, c}); // Returns `{ a: 1, b: 2, c: 3 }`
});
window.fire('test', [1, 2, 3], new Set([1, 2, 3]));
Return the added hooks.
console.log(window.hooks);
Remove a hook.
Remove all window-resize
hooks.
window.off('window-resize');
Remove onWindowResize
hook from window-resize
event.
window.off('window-resize', onWindowResize);
Add a hook.
Add window-resize
hook anonymously.
window.on('window-resize', data => {
console.log([
data.height,
data.width
]);
});
Add window-resize
hook with named function.
function onWindowResize(data) {
console.log([
data.height,
data.width
]);
}
window.on('window-resize', onWindowResize);
Extend the hook system to an application.
import {hook} from '@taufik-nurrohman/hook';
class Widget {
constructor() {
this.#data = [];
// This will create `fire`, `hooks`, `off`, and `on` properties
hook(this, this.constructor.prototype);
}
append(datum) {
this.#data.push(datum);
this.fire('update', [datum]);
return this;
}
create(data) {
this.#data = data;
this.fire('create');
return this;
}
destroy() {
this.fire('destroy');
return this;
}
prepend(datum) {
this.#data.unshift(datum);
this.fire('update', [datum]);
return this;
}
}
const widget = new Widget;
widget.on('create', () => {
console.log('Created!');
});
widget.on('destroy', () => {
console.log('Destroyed!');
});
widget.on('update', datum => {
console.log('Added ' + datum);
});
widget.create([1, 2, 3]);
widget.append(4).append(5).append(6);
// `Created!`
// `Added 4`
// `Added 5`
// `Added 6`