Skip to content

Instantly share code, notes, and snippets.

@marlun78
Last active August 29, 2015 14:00
Show Gist options
  • Save marlun78/11173518 to your computer and use it in GitHub Desktop.
Save marlun78/11173518 to your computer and use it in GitHub Desktop.
Minimal Events
/**
* Minimal Events
* Copyright (c) 2013 marlun78
* MIT License, https://gist.github.com/marlun78/bd0800cf5e8053ba9f83
*/
// TODO: Rework “once”
window.evts = (function () {
'use strict';
var MUST_BE_A_FUNCTION = 'The event handler must be a function',
toString = {}.toString,
map = {};
function emit(type, data) {
each(map[type], function (item, index, items) {
item(data);
if (item.__once__ === true) {
delete item.__once__;
remove(items, index);
}
});
}
function once(type, handler) {
if (!isFunction(handler)) {
throw new TypeError(MUST_BE_A_FUNCTION);
}
handler.__once__ = true; // Wont work if frozen...
return on(type, handler);
}
function on(type, handler) {
if (!isFunction(handler)) {
throw new TypeError(MUST_BE_A_FUNCTION);
}
store(type, handler);
return function () {
off(type, handler);
};
}
//Pass true as the second argument to remove all handlers of one type
function off(type, handler) {
if (handler === true) {
map[type] = [];
return;
}
each(map[type], function (item, index, items) {
if (item === handler) {
remove(items, index);
}
});
}
function store(type, handler) {
if (!isArray(map[type])) {
map[type] = [];
}
map[type].push(handler);
}
function remove(items, index) {
items.splice(index, 1);
}
function each(items, iterator) {
var index, count;
for (index = 0, count = items.length; index < count; index++) {
iterator(items[index], index, items);
}
}
function isArray(value) {
return toString.call(value) === '[object Array]';
}
function isFunction(value) {
return typeof value === 'function';
}
return {
emit: emit,
once: once,
on: on,
off: off
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment