UNPKG

2.07 kBJavaScriptView Raw
1/**
2 * MicroEvent - to make any js object an event emitter (server or browser)
3 *
4 * - pure javascript - server compatible, browser compatible
5 * - dont rely on the browser doms
6 * - super simple - you get it immediately, no mystery, no magic involved
7 *
8 * - create a MicroEventDebug with goodies to debug
9 * - make it safer to use
10*/
11
12/** NOTE: This library is customized for Onsen UI. */
13
14const MicroEvent = function(){};
15MicroEvent.prototype = {
16 on: function(event, fct){
17 this._events = this._events || {};
18 this._events[event] = this._events[event] || [];
19 this._events[event].push(fct);
20 },
21 once: function(event, fct){
22 var self = this;
23 var wrapper = function() {
24 self.off(event, wrapper);
25 return fct.apply(null, arguments);
26 };
27 this.on(event, wrapper);
28 },
29 off: function(event, fct){
30 this._events = this._events || {};
31 if (event in this._events === false) {
32 return;
33 }
34
35 this._events[event] = this._events[event]
36 .filter(function(_fct) {
37 if (fct) {
38 return fct !== _fct;
39 }
40 else {
41 return false;
42 }
43 });
44 },
45 emit: function(event /* , args... */){
46 this._events = this._events || {};
47 if (event in this._events === false) {
48 return;
49 }
50 for (var i = 0; i < this._events[event].length; i++){
51 this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
52 }
53 }
54};
55
56/**
57 * mixin will delegate all MicroEvent.js function in the destination object
58 *
59 * - require('MicroEvent').mixin(Foobar) will make Foobar able to use MicroEvent
60 *
61 * @param {Object} the object which will support MicroEvent
62*/
63MicroEvent.mixin = function(destObject){
64 var props = ['on', 'once', 'off', 'emit'];
65 for (var i = 0; i < props.length; i ++){
66 if (typeof destObject === 'function') {
67 destObject.prototype[props[i]] = MicroEvent.prototype[props[i]];
68 } else {
69 destObject[props[i]] = MicroEvent.prototype[props[i]];
70 }
71 }
72};
73
74window.MicroEvent = MicroEvent;
75export default MicroEvent;