Skip to content

Instantly share code, notes, and snippets.

@SaulDoesCode
Created July 25, 2016 14:01
Show Gist options
  • Save SaulDoesCode/32ac8c69c76d6dcba8c5f0141acab290 to your computer and use it in GitHub Desktop.
Save SaulDoesCode/32ac8c69c76d6dcba8c5f0141acab290 to your computer and use it in GitHub Desktop.
some simple abstraction over target.addEventListener
const eventListener = (target, type, handle) => ({
on(alt, options) {
if (typeof alt != "function") {
options = alt;
alt = null;
}
this.active = true;
this.options = options != undefined ? options : this.options || false;
if (target.addEventListener) target.addEventListener(type, alt || handle, this.options);
return this;
},
once(options) {
this.off();
if (target.addEventListener) {
const listener = this;
function wrapper() {
handle.apply(this, arguments);
listener.off(wrapper);
}
listener.on(wrapper, options)
}
return this;
},
off(alt) {
if (this.active) {
this.active = false;
if (target.removeEventListener) target.removeEventListener(type, typeof alt === "function" ? alt : handle, this.options);
}
return this;
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment