JavaScript - CallbackBundler
A tool to bundle callbacks and attach to any object that supports event listener.
Install
npm
It's recommended to install it as dependency.
npm install --save callbackbundler
browser
Download the callbackbundler.min.js file and include it in your HTML.
<script src="path/to/src/callbackbundler.min.js"></script>
Usage
CommonJS
var CallbackBundler = require('callbackbundler');
var bundle = new CallbackBundler();
Browser
<script>
var bundle = new CallbackBundler();
</script>
API
CallbackBundler is extended from Array.prototype. Therefore, apart from the methods listed below, it can use every Array instance's methods that environment supports. Although, it is not recommended as it might generate unexpected result if handled carelessly.
The examples below will use the functions and variables defined below:
var bundle = new CallbackBundler();
function callback1(){
console.log(1);
}
function callback2(){
console.log(this);
}
function callback(e, v){
console.log(e, v);
}
.add
bundle.add(callback1);
bundle.add(callback2);
bundle.add(callback3);
bundle.add(callback1, callback2, callback3);
.attach
var elem = document.body,
api = 'addEventListener',
type = 'click',
otherArgs = { once: true }
bundle.attach(elem, api, type, otherArgs);
.detach
var elem = document.body,
api = 'removeEventListener',
type = 'click';
bundle.detach(elem, api, type);
.run
bundle.run('thisVal', [
undefined,
undefined,
['argument 0', true]
]);
Caveat: You need to keep track on the indexes of each callback that you bundled to accurately pass arguments.
.size
console.log(bundle.size);
Note: You can also use bundle.length.
.remove
bundle.remove(callback1);
bundle.remove(callback2);
bundle.remove(callback3);
bundle.remove(callback1, callback2, callback3);
Note: Removing callback(s) will not remove it from previously attached event listener. Use with care.
Actual use case?
It will be useful if:
- You are building a web app that involves a lot of dynamically created while reactive elements.
- You are not using any JavaScript libraries (i.e., jQuery, etc).