1.0.13 • Published 5 years ago
tw-emitter v1.0.13
tw-emitter
A little useful emitter.
Install
on NPM
npm install tw-emitter
import Emitter from 'tw-emitter';
on Browser
<script src="/path/to/dist/Emitter.min.js"></script>
Usage
Basic
const f = a => {
console.log('ev', a);
};
new Emitter()
.on('ev', f)
.emit('ev', 1) // ev 1
.off('ev', f)
.emit('ev', 1) // (nothing)
Basic once
new Emitter()
.once('ev', a => {
console.log('ev', a);
})
.emit('ev', 1) // ev 1
.emit('ev', 1) // (nothing)
Repeatable arguments
new Emitter()
.on('ev', (...args) => {
console.log('ev', ...args);
})
.emit('ev', 1, 2, 3, 4, 5, 6, 7) // ev 1 2 3 4 5 6 7
Specify the context
new Emitter()
.on('ev', function(a) {
console.log(this, a);
})
.cemit('ev', {hoge: 1}, 2) // {hoge: 1} 2
However, using the arrow function invalidates the context specification.
// on window
new Emitter()
.on('ev', a => {
console.log(this, a);
})
.cemit('ev', {hoge: 1}, 2) // Window 2
Events delete in groups
new Emitter()
.on('ev', a => {
console.log('ev', a);
})
.on('ev', a => {
console.log('ev', a);
})
.on('ev2', a => {
console.log('ev', a);
})
.on('ev2', a => {
console.log('ev', a);
})
.clear('ev')
.emit('ev', 1) // (nothing)
.emit('ev2', 1) // ev 1, ev 1
All events delete at once
new Emitter()
.on('ev', a => {
console.log('ev', a);
})
.on('ev2', a => {
console.log('ev', a);
})
.on('ev3', a => {
console.log('ev', a);
})
.on('ev4', a => {
console.log('ev', a);
})
.clear()
.emit('ev', 1) // (nothing)
.emit('ev2', 1) // (nothing)
.emit('ev3', 1) // (nothing)
.emit('ev4', 1) // (nothing)