Last active
August 29, 2015 14:07
-
-
Save tunnckoCore/ff914b679452356d805b to your computer and use it in GitHub Desktop.
DualEmitter.js cross-browser + node.js event emitter. Invoke custom or DOM event. Micro library in 35lines without jQuery!!!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function (name, that, fn) { | |
if (typeof module !== 'undefined') { | |
module.exports = fn(); | |
} else if (typeof define === 'function' && define.amd) { | |
define(fn); | |
} else { | |
that[name] = fn(); | |
} | |
})('DualEmitter', this, function DualEmitter($) { | |
$ = $ || this; | |
$.events = $.events || {}; | |
$.hasEvent = function hasEvent(name) { | |
return (name in $.events) ? $.events[name] : 0; | |
}; | |
$.isDom = function isDom(obj) { | |
obj = Object.prototype.toString.call(obj).slice(8, -1); | |
return /HTML(?:.*)Element/.test(obj); | |
}; | |
$.on = function on(name, fn, func) { | |
if (typeof name !== 'string' || $.isDom(name)) { | |
if (name.attachListener) { | |
name.attachListener('on' + fn, func, false); | |
return $; | |
} | |
name.addEventListener(fn, func, false); | |
$.events['i:' + fn] = func; | |
return $; | |
} | |
$.events[name] = fn; | |
return $; | |
}; | |
$.off = function off(name) { | |
if(!$.hasEvent(name)) {delete $.events[name];} | |
return $; | |
}; | |
$.emit = function emit(args) { | |
args = [].slice.call(arguments); | |
args.shift().split(' ').forEach(function(e) { | |
$.hasEvent(e).apply(this, args); | |
}); | |
return $; | |
}; | |
return $; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var dualEmitter = new DualEmitter(); | |
dualEmitter | |
.on('test', function(one, two, arr, obj) { | |
console.log('test', one, two, arr, obj); | |
console.log('------------'); | |
}) | |
.on(document.querySelector('.customh1'), 'click', function(el, arg1, arg2) { | |
console.log('you emit DOM event', el.textContent, arg1, arg2); | |
console.log('------------'); | |
}) | |
.emit('test', 1, 2, [3, 4, 5], {six: 'seven'}) | |
// or you can emit DOM event with `i:` prefix, followed by event name | |
.emit('i:click', document.querySelector('.customDiv'), 'arg1', 'arg2') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment