@x-oasis/emitter 0.1.35 → 0.1.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(){function s(){this.subscriptions={}}var t=s.prototype;return t.fire=function(s){for(var t=this.subscriptions[s]||[],i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];for(var e=0;e<t.length;e++)t[e].apply(this,n)},t.on=function(s,t){var i=this;return this.subscriptions[s]?this.subscriptions[s].push(t):this.subscriptions[s]=[t],function(){var n=i.subscriptions[s],r=n.indexOf(t);-1!==r&&n.splice(r,1)}},t.off=function(s){delete this.subscriptions[s]},s}();
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@x-oasis/disposable");function t(){return(t=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e}).apply(this,arguments)}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=new Array(t);r<t;r++)i[r]=e[r];return i}function i(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(i)return(i=i.call(e)).next.bind(i);if(Array.isArray(e)||(i=function(e,t){if(e){if("string"==typeof e)return r(e,void 0);var i=Object.prototype.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?r(e,void 0):void 0}}(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n=function(){function t(e){this._listeners=[];var t=e.onWillAddFirstListener,r=e.onDidAddFirstListener,i=e.onDidAddListener,n=e.onWillRemoveListener,s=e.onDidRemoveLastListener,o=e.coldTrigger;this.name=e.name,this._coldTrigger=o,this._onWillAddFirstListener=t,this._onDidAddFirstListener=r,this._onDidAddListener=i,this._onWillRemoveListener=n,this._onDidRemoveLastListener=s,this.subscribe=this.subscribe.bind(this)}var r=t.prototype;return r.subscribe=function(t){var r,i,n,s=this;return this._listeners.length||null==(r=this._onWillAddFirstListener)||r.call(this),-1!==this._listeners.indexOf(t)?console.error("add a duplicate listener"):(this._listeners.push(t),1===this._listeners.length&&(null==(i=this._onDidAddFirstListener)||i.call(this)),null==(n=this._onDidAddListener)||n.call(this),this._coldTrigger&&this._cacheCurrentValue&&t.apply(void 0,this._cacheCurrentValue)),e.toDisposable((function(){s.removeListener(t)}))},r.removeListener=function(e){var t,r,i=this._listeners.indexOf(e);-1!==i&&(null==(t=this._onWillRemoveListener)||t.call(this),this._listeners.splice(i,1),this._listeners.length||null==(r=this._onDidRemoveLastListener)||r.call(this))},r.dispose=function(){var e;this._listeners=[],null==(e=this._onDidRemoveLastListener)||e.call(this)},r.fire=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this._coldTrigger&&(this._cacheCurrentValue=t);for(var n,s=i(this._listeners);!(n=s()).done;){var o=n.value;o.apply(void 0,t)}},t}();exports.Emitter=function(){function e(e){this._events=new Map,this._disposed=!1,this._name=(e||{}).name}var r,s,o=e.prototype;return o.register=function(e,r){return this._events.has(e)||this._events.set(e,new n(t({},r||{},{name:e}))),this._events.get(e)},o.getEvent=function(e){return this._events.get(e)},o.dispose=function(){if(!this._disposed){for(var e,t=i(this._events);!(e=t()).done;)e.value[1].dispose();this._disposed=!0}},r=e,(s=[{key:"name",get:function(){return this._name}}])&&function(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,"symbol"==typeof(n=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(i.key))?n:String(n),i)}var n}(r.prototype,s),Object.defineProperty(r,"prototype",{writable:!1}),e}(),exports.Event=n,exports.fromNodeEvent=function(e,t){var r=new n({name:t,onWillAddFirstListener:function(){return e.on(t,i)},onDidRemoveLastListener:function(){return e.removeListener(t,i)}}),i=function(){return r.fire.apply(r,arguments)};return r.subscribe};
2
2
  //# sourceMappingURL=emitter.cjs.production.min.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"emitter.cjs.production.min.js","sources":["../src/index.ts"],"sourcesContent":["class Emitter {\n public subscriptions: {\n [key: string]: any;\n } = {};\n\n fire(event, ...rest) {\n const cbs = this.subscriptions[event] || [];\n for (let i = 0; i < cbs.length; i++) {\n cbs[i].apply(this, rest); // eslint-disable-line\n }\n }\n\n on(event, cb) {\n if (!this.subscriptions[event]) this.subscriptions[event] = [cb];\n else this.subscriptions[event].push(cb);\n\n return () => {\n const subscriptions = this.subscriptions[event];\n const index = subscriptions.indexOf(cb);\n if (index !== -1) subscriptions.splice(index, 1);\n };\n }\n\n off(event) {\n delete this.subscriptions[event];\n }\n}\n\nexport default Emitter;\n"],"names":["Emitter","this","_proto","prototype","fire","event","cbs","subscriptions","_len","arguments","length","rest","Array","_key","i","apply","on","cb","push","_this","index","indexOf","splice","off"],"mappings":"+FAAA,SAAAA,IACSC,mBAEH,GAuBL,IAAAC,EAAAF,EAAAG,UADE,OACFD,EArBCE,KAAA,SAAKC,GACyC,IAA5C,IAAMC,EAAML,KAAKM,cAAcF,IAAU,GAAGG,EAAAC,UAAAC,OAD/BC,MAAIC,MAAAJ,IAAAA,OAAAK,IAAAA,EAAAL,EAAAK,IAAJF,EAAIE,KAAAJ,UAAAI,GAEjB,IAAK,IAAIC,EAAI,EAAGA,EAAIR,EAAII,OAAQI,IAC9BR,EAAIQ,GAAGC,MAAMd,KAAMU,IAEtBT,EAEDc,GAAA,SAAGX,EAAOY,cAIR,OAHKhB,KAAKM,cAAcF,GACnBJ,KAAKM,cAAcF,GAAOa,KAAKD,GADJhB,KAAKM,cAAcF,GAAS,CAACY,GAGtD,WACL,IAAMV,EAAgBY,EAAKZ,cAAcF,GACnCe,EAAQb,EAAcc,QAAQJ,IACrB,IAAXG,GAAcb,EAAce,OAAOF,EAAO,KAEjDlB,EAEDqB,IAAA,SAAIlB,UACKJ,KAAKM,cAAcF,IAC3BL"}
1
+ {"version":3,"file":"emitter.cjs.production.min.js","sources":["../src/Event.ts","../src/Emitter.ts","../src/fromNodeEvent.ts"],"sourcesContent":["import { toDisposable } from '@x-oasis/disposable';\nimport { EventListener, EventProps } from './types';\n\nexport default class Event {\n readonly name: string;\n\n private _listeners: EventListener[] = [];\n\n private _onWillAddFirstListener?: Function;\n\n private _onDidAddFirstListener?: Function;\n\n private _onDidAddListener?: Function;\n\n private _onWillRemoveListener?: Function;\n\n private _onDidRemoveLastListener?: Function;\n\n private _coldTrigger?: boolean;\n\n private _cacheCurrentValue?: any[] | undefined;\n\n constructor(props: EventProps & { name: string }) {\n const {\n name,\n onWillAddFirstListener,\n onDidAddFirstListener,\n onDidAddListener,\n onWillRemoveListener,\n onDidRemoveLastListener,\n coldTrigger,\n } = props;\n\n this.name = name;\n\n this._coldTrigger = coldTrigger;\n this._onWillAddFirstListener = onWillAddFirstListener;\n this._onDidAddFirstListener = onDidAddFirstListener;\n this._onDidAddListener = onDidAddListener;\n this._onWillRemoveListener = onWillRemoveListener;\n this._onDidRemoveLastListener = onDidRemoveLastListener;\n this.subscribe = this.subscribe.bind(this);\n }\n\n subscribe(listener: EventListener) {\n if (!this._listeners.length) {\n this._onWillAddFirstListener?.();\n }\n\n const index = this._listeners.indexOf(listener);\n if (index !== -1) {\n console.error('add a duplicate listener');\n } else {\n this._listeners.push(listener);\n if (this._listeners.length === 1) this._onDidAddFirstListener?.();\n this._onDidAddListener?.();\n if (this._coldTrigger && this._cacheCurrentValue)\n listener(...this._cacheCurrentValue);\n }\n\n return toDisposable(() => {\n this.removeListener(listener);\n });\n }\n\n removeListener(listener: EventListener) {\n const index = this._listeners.indexOf(listener);\n if (index === -1) return;\n this._onWillRemoveListener?.();\n\n this._listeners.splice(index, 1);\n if (!this._listeners.length) {\n this._onDidRemoveLastListener?.();\n }\n }\n\n dispose() {\n this._listeners = [];\n this._onDidRemoveLastListener?.();\n }\n\n fire(...args: any[]) {\n if (this._coldTrigger) {\n this._cacheCurrentValue = args;\n }\n for (const listener of this._listeners) {\n listener(...args);\n }\n }\n}\n","import Event from './Event';\nimport { EventProps } from './types';\n\nexport default class Emitter {\n private _events = new Map<string, Event>();\n\n private _disposed = false;\n\n private _name: string;\n\n constructor(props: { name: string }) {\n const { name } = props || {};\n this._name = name;\n }\n\n get name() {\n return this._name;\n }\n\n /**\n * 没有就注册,有就返回\n */\n register(eventName: string, eventProps?: EventProps) {\n if (this._events.has(eventName)) {\n return this._events.get(eventName) as Event;\n }\n\n this._events.set(\n eventName,\n new Event({\n ...(eventProps || {}),\n name: eventName,\n })\n );\n\n return this._events.get(eventName) as Event;\n }\n\n getEvent(eventName: string) {\n return this._events.get(eventName);\n }\n\n dispose() {\n if (this._disposed) return;\n for (const [_, event] of this._events) {\n event.dispose();\n }\n\n this._disposed = true;\n }\n}\n\nexport type IEvent = Event;\n","import Event from './Event';\n\nexport interface NodeEventEmitter {\n on(event: string | symbol, listener: Function): unknown;\n removeListener(event: string | symbol, listener: Function): unknown;\n}\n\n/**\n * Creates an {@link Event} from a node event emitter.\n */\nexport function fromNodeEvent(emitter: NodeEventEmitter, eventName: string) {\n // @ts-ignore\n const onFirstListenerAdd = () => emitter.on(eventName, fn);\n const onLastListenerRemove = () => emitter.removeListener(eventName, fn);\n const event = new Event({\n name: eventName,\n onWillAddFirstListener: onFirstListenerAdd,\n onDidRemoveLastListener: onLastListenerRemove,\n });\n\n const fn = (...args: any[]) => {\n return event.fire(...args);\n };\n\n return event.subscribe;\n}\n"],"names":["Event","props","this","onWillAddFirstListener","onDidAddFirstListener","onDidAddListener","onWillRemoveListener","onDidRemoveLastListener","coldTrigger","name","_coldTrigger","_onWillAddFirstListener","_onDidAddFirstListener","_onDidAddListener","_onWillRemoveListener","_onDidRemoveLastListener","subscribe","bind","_proto","prototype","listener","_this$_onWillAddFirst","_this$_onDidAddFirstL","_this$_onDidAddListen","_listeners","length","call","indexOf","console","error","push","_cacheCurrentValue","apply","toDisposable","_this","removeListener","_this$_onDidRemoveLas","index","_this$_onWillRemoveLi","splice","dispose","_this$_onDidRemoveLas2","fire","args","Array","_len","_key","arguments","_step","_iterator","_createForOfIteratorHelperLoose","done","value","Emitter","Map","_name","register","eventName","eventProps","_events","has","set","_extends","get","getEvent","_disposed","key","emitter","event","on","fn"],"mappings":"gpCAGqBA,aAmBnB,SAAAA,EAAYC,GAhBJC,gBAA8B,GAiBpC,IAEEC,EAMEF,EANFE,uBACAC,EAKEH,EALFG,sBACAC,EAIEJ,EAJFI,iBACAC,EAGEL,EAHFK,qBACAC,EAEEN,EAFFM,wBACAC,EACEP,EADFO,YAGFN,KAAKO,KAFDR,EAPFQ,KAWFP,KAAKQ,aAAeF,EACpBN,KAAKS,wBAA0BR,EAC/BD,KAAKU,uBAAyBR,EAC9BF,KAAKW,kBAAoBR,EACzBH,KAAKY,sBAAwBR,EAC7BJ,KAAKa,yBAA2BR,EAChCL,KAAKc,UAAYd,KAAKc,UAAUC,KAAKf,MACtC,IAAAgB,EAAAlB,EAAAmB,UA8CA,OA9CAD,EAEDF,UAAA,SAAUI,OACqBC,EAOtBC,EAAAC,SAQP,OAfKrB,KAAKsB,WAAWC,eACnBJ,OAAKV,0BAALU,EAAAK,YAIa,IADDxB,KAAKsB,WAAWG,QAAQP,GAEpCQ,QAAQC,MAAM,6BAEd3B,KAAKsB,WAAWM,KAAKV,GACU,IAA3BlB,KAAKsB,WAAWC,gBAAcH,OAAKV,yBAALU,EAA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I,SAC/BZ,UAGRtC,KAAK+D,WAAY,MAClBZ,OAAAa,WAAAH,IAlCD,WACE,OAAO7D,KAAKqD,wgBACbF,oDCP2Bc,EAA2BV,GAEvD,IAEMW,EAAQ,IAAIpE,EAAM,CACtBS,KAAMgD,EACNtD,uBAJyB,WAAH,OAASgE,EAAQE,GAAGZ,EAAWa,IAKrD/D,wBAJ2B,WAAH,OAAS4D,EAAQhC,eAAesB,EAAWa,MAO/DA,EAAK,WACT,OAAOF,EAAM1B,KAAIV,MAAVoC,EAAKrB,YAGd,OAAOqB,EAAMpD"}
@@ -1,31 +1,209 @@
1
- var Emitter = /*#__PURE__*/function () {
2
- function Emitter() {
3
- this.subscriptions = {};
1
+ import { toDisposable } from '@x-oasis/disposable';
2
+
3
+ function _defineProperties(target, props) {
4
+ for (var i = 0; i < props.length; i++) {
5
+ var descriptor = props[i];
6
+ descriptor.enumerable = descriptor.enumerable || false;
7
+ descriptor.configurable = true;
8
+ if ("value" in descriptor) descriptor.writable = true;
9
+ Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
4
10
  }
5
- var _proto = Emitter.prototype;
6
- _proto.fire = function fire(event) {
7
- var cbs = this.subscriptions[event] || [];
8
- for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
9
- rest[_key - 1] = arguments[_key];
10
- }
11
- for (var i = 0; i < cbs.length; i++) {
12
- cbs[i].apply(this, rest);
11
+ }
12
+ function _createClass(Constructor, protoProps, staticProps) {
13
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
14
+ if (staticProps) _defineProperties(Constructor, staticProps);
15
+ Object.defineProperty(Constructor, "prototype", {
16
+ writable: false
17
+ });
18
+ return Constructor;
19
+ }
20
+ function _extends() {
21
+ _extends = Object.assign ? Object.assign.bind() : function (target) {
22
+ for (var i = 1; i < arguments.length; i++) {
23
+ var source = arguments[i];
24
+ for (var key in source) {
25
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
26
+ target[key] = source[key];
27
+ }
28
+ }
13
29
  }
30
+ return target;
14
31
  };
15
- _proto.on = function on(event, cb) {
16
- var _this = this;
17
- if (!this.subscriptions[event]) this.subscriptions[event] = [cb];else this.subscriptions[event].push(cb);
32
+ return _extends.apply(this, arguments);
33
+ }
34
+ function _unsupportedIterableToArray(o, minLen) {
35
+ if (!o) return;
36
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
37
+ var n = Object.prototype.toString.call(o).slice(8, -1);
38
+ if (n === "Object" && o.constructor) n = o.constructor.name;
39
+ if (n === "Map" || n === "Set") return Array.from(o);
40
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
41
+ }
42
+ function _arrayLikeToArray(arr, len) {
43
+ if (len == null || len > arr.length) len = arr.length;
44
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
45
+ return arr2;
46
+ }
47
+ function _createForOfIteratorHelperLoose(o, allowArrayLike) {
48
+ var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
49
+ if (it) return (it = it.call(o)).next.bind(it);
50
+ if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
51
+ if (it) o = it;
52
+ var i = 0;
18
53
  return function () {
19
- var subscriptions = _this.subscriptions[event];
20
- var index = subscriptions.indexOf(cb);
21
- if (index !== -1) subscriptions.splice(index, 1);
54
+ if (i >= o.length) return {
55
+ done: true
56
+ };
57
+ return {
58
+ done: false,
59
+ value: o[i++]
60
+ };
22
61
  };
62
+ }
63
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
64
+ }
65
+ function _toPrimitive(input, hint) {
66
+ if (typeof input !== "object" || input === null) return input;
67
+ var prim = input[Symbol.toPrimitive];
68
+ if (prim !== undefined) {
69
+ var res = prim.call(input, hint || "default");
70
+ if (typeof res !== "object") return res;
71
+ throw new TypeError("@@toPrimitive must return a primitive value.");
72
+ }
73
+ return (hint === "string" ? String : Number)(input);
74
+ }
75
+ function _toPropertyKey(arg) {
76
+ var key = _toPrimitive(arg, "string");
77
+ return typeof key === "symbol" ? key : String(key);
78
+ }
79
+
80
+ var Event = /*#__PURE__*/function () {
81
+ function Event(props) {
82
+ this._listeners = [];
83
+ var name = props.name,
84
+ onWillAddFirstListener = props.onWillAddFirstListener,
85
+ onDidAddFirstListener = props.onDidAddFirstListener,
86
+ onDidAddListener = props.onDidAddListener,
87
+ onWillRemoveListener = props.onWillRemoveListener,
88
+ onDidRemoveLastListener = props.onDidRemoveLastListener,
89
+ coldTrigger = props.coldTrigger;
90
+ this.name = name;
91
+ this._coldTrigger = coldTrigger;
92
+ this._onWillAddFirstListener = onWillAddFirstListener;
93
+ this._onDidAddFirstListener = onDidAddFirstListener;
94
+ this._onDidAddListener = onDidAddListener;
95
+ this._onWillRemoveListener = onWillRemoveListener;
96
+ this._onDidRemoveLastListener = onDidRemoveLastListener;
97
+ this.subscribe = this.subscribe.bind(this);
98
+ }
99
+ var _proto = Event.prototype;
100
+ _proto.subscribe = function subscribe(listener) {
101
+ var _this = this;
102
+ if (!this._listeners.length) {
103
+ var _this$_onWillAddFirst;
104
+ (_this$_onWillAddFirst = this._onWillAddFirstListener) == null ? void 0 : _this$_onWillAddFirst.call(this);
105
+ }
106
+ var index = this._listeners.indexOf(listener);
107
+ if (index !== -1) {
108
+ console.error('add a duplicate listener');
109
+ } else {
110
+ var _this$_onDidAddFirstL, _this$_onDidAddListen;
111
+ this._listeners.push(listener);
112
+ if (this._listeners.length === 1) (_this$_onDidAddFirstL = this._onDidAddFirstListener) == null ? void 0 : _this$_onDidAddFirstL.call(this);
113
+ (_this$_onDidAddListen = this._onDidAddListener) == null ? void 0 : _this$_onDidAddListen.call(this);
114
+ if (this._coldTrigger && this._cacheCurrentValue) listener.apply(void 0, this._cacheCurrentValue);
115
+ }
116
+ return toDisposable(function () {
117
+ _this.removeListener(listener);
118
+ });
119
+ };
120
+ _proto.removeListener = function removeListener(listener) {
121
+ var _this$_onWillRemoveLi;
122
+ var index = this._listeners.indexOf(listener);
123
+ if (index === -1) return;
124
+ (_this$_onWillRemoveLi = this._onWillRemoveListener) == null ? void 0 : _this$_onWillRemoveLi.call(this);
125
+ this._listeners.splice(index, 1);
126
+ if (!this._listeners.length) {
127
+ var _this$_onDidRemoveLas;
128
+ (_this$_onDidRemoveLas = this._onDidRemoveLastListener) == null ? void 0 : _this$_onDidRemoveLas.call(this);
129
+ }
23
130
  };
24
- _proto.off = function off(event) {
25
- delete this.subscriptions[event];
131
+ _proto.dispose = function dispose() {
132
+ var _this$_onDidRemoveLas2;
133
+ this._listeners = [];
134
+ (_this$_onDidRemoveLas2 = this._onDidRemoveLastListener) == null ? void 0 : _this$_onDidRemoveLas2.call(this);
26
135
  };
136
+ _proto.fire = function fire() {
137
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
138
+ args[_key] = arguments[_key];
139
+ }
140
+ if (this._coldTrigger) {
141
+ this._cacheCurrentValue = args;
142
+ }
143
+ for (var _iterator = _createForOfIteratorHelperLoose(this._listeners), _step; !(_step = _iterator()).done;) {
144
+ var listener = _step.value;
145
+ listener.apply(void 0, args);
146
+ }
147
+ };
148
+ return Event;
149
+ }();
150
+
151
+ var Emitter = /*#__PURE__*/function () {
152
+ function Emitter(props) {
153
+ this._events = new Map();
154
+ this._disposed = false;
155
+ var _ref = props || {},
156
+ name = _ref.name;
157
+ this._name = name;
158
+ }
159
+ var _proto = Emitter.prototype;
160
+ _proto.register = function register(eventName, eventProps) {
161
+ if (this._events.has(eventName)) {
162
+ return this._events.get(eventName);
163
+ }
164
+ this._events.set(eventName, new Event(_extends({}, eventProps || {}, {
165
+ name: eventName
166
+ })));
167
+ return this._events.get(eventName);
168
+ };
169
+ _proto.getEvent = function getEvent(eventName) {
170
+ return this._events.get(eventName);
171
+ };
172
+ _proto.dispose = function dispose() {
173
+ if (this._disposed) return;
174
+ for (var _iterator = _createForOfIteratorHelperLoose(this._events), _step; !(_step = _iterator()).done;) {
175
+ var _step$value = _step.value,
176
+ event = _step$value[1];
177
+ event.dispose();
178
+ }
179
+ this._disposed = true;
180
+ };
181
+ _createClass(Emitter, [{
182
+ key: "name",
183
+ get: function get() {
184
+ return this._name;
185
+ }
186
+ }]);
27
187
  return Emitter;
28
188
  }();
29
189
 
30
- export default Emitter;
190
+ function fromNodeEvent(emitter, eventName) {
191
+ var onFirstListenerAdd = function onFirstListenerAdd() {
192
+ return emitter.on(eventName, fn);
193
+ };
194
+ var onLastListenerRemove = function onLastListenerRemove() {
195
+ return emitter.removeListener(eventName, fn);
196
+ };
197
+ var event = new Event({
198
+ name: eventName,
199
+ onWillAddFirstListener: onFirstListenerAdd,
200
+ onDidRemoveLastListener: onLastListenerRemove
201
+ });
202
+ var fn = function fn() {
203
+ return event.fire.apply(event, arguments);
204
+ };
205
+ return event.subscribe;
206
+ }
207
+
208
+ export { Emitter, Event, fromNodeEvent };
31
209
  //# sourceMappingURL=emitter.esm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"emitter.esm.js","sources":["../src/index.ts"],"sourcesContent":["class Emitter {\n public subscriptions: {\n [key: string]: any;\n } = {};\n\n fire(event, ...rest) {\n const cbs = this.subscriptions[event] || [];\n for (let i = 0; i < cbs.length; i++) {\n cbs[i].apply(this, rest); // eslint-disable-line\n }\n }\n\n on(event, cb) {\n if (!this.subscriptions[event]) this.subscriptions[event] = [cb];\n else this.subscriptions[event].push(cb);\n\n return () => {\n const subscriptions = this.subscriptions[event];\n const index = subscriptions.indexOf(cb);\n if (index !== -1) subscriptions.splice(index, 1);\n };\n }\n\n off(event) {\n delete this.subscriptions[event];\n }\n}\n\nexport default Emitter;\n"],"names":["Emitter","_proto","prototype","fire","event","cbs","subscriptions","_len","arguments","length","rest","Array","_key","i","apply","on","cb","push","_this","index","indexOf","splice","off"],"mappings":"IAAMA,OAAO;EAAb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AAAJ,OAAA;AAAA;;;;"}
1
+ {"version":3,"file":"emitter.esm.js","sources":["../src/Event.ts","../src/Emitter.ts","../src/fromNodeEvent.ts"],"sourcesContent":["import { toDisposable } from '@x-oasis/disposable';\nimport { EventListener, EventProps } from './types';\n\nexport default class Event {\n readonly name: string;\n\n private _listeners: EventListener[] = [];\n\n private _onWillAddFirstListener?: Function;\n\n private _onDidAddFirstListener?: Function;\n\n private _onDidAddListener?: Function;\n\n private _onWillRemoveListener?: Function;\n\n private _onDidRemoveLastListener?: Function;\n\n private _coldTrigger?: boolean;\n\n private _cacheCurrentValue?: any[] | undefined;\n\n constructor(props: EventProps & { name: string }) {\n const {\n name,\n onWillAddFirstListener,\n onDidAddFirstListener,\n onDidAddListener,\n onWillRemoveListener,\n onDidRemoveLastListener,\n coldTrigger,\n } = props;\n\n this.name = name;\n\n this._coldTrigger = coldTrigger;\n this._onWillAddFirstListener = onWillAddFirstListener;\n this._onDidAddFirstListener = onDidAddFirstListener;\n this._onDidAddListener = onDidAddListener;\n this._onWillRemoveListener = onWillRemoveListener;\n this._onDidRemoveLastListener = onDidRemoveLastListener;\n this.subscribe = this.subscribe.bind(this);\n }\n\n subscribe(listener: EventListener) {\n if (!this._listeners.length) {\n this._onWillAddFirstListener?.();\n }\n\n const index = this._listeners.indexOf(listener);\n if (index !== -1) {\n console.error('add a duplicate listener');\n } else {\n this._listeners.push(listener);\n if (this._listeners.length === 1) this._onDidAddFirstListener?.();\n this._onDidAddListener?.();\n if (this._coldTrigger && this._cacheCurrentValue)\n listener(...this._cacheCurrentValue);\n }\n\n return toDisposable(() => {\n this.removeListener(listener);\n });\n }\n\n removeListener(listener: EventListener) {\n const index = this._listeners.indexOf(listener);\n if (index === -1) return;\n this._onWillRemoveListener?.();\n\n this._listeners.splice(index, 1);\n if (!this._listeners.length) {\n this._onDidRemoveLastListener?.();\n }\n }\n\n dispose() {\n this._listeners = [];\n this._onDidRemoveLastListener?.();\n }\n\n fire(...args: any[]) {\n if (this._coldTrigger) {\n this._cacheCurrentValue = args;\n }\n for (const listener of this._listeners) {\n listener(...args);\n }\n }\n}\n","import Event from './Event';\nimport { EventProps } from './types';\n\nexport default class Emitter {\n private _events = new Map<string, Event>();\n\n private _disposed = false;\n\n private _name: string;\n\n constructor(props: { name: string }) {\n const { name } = props || {};\n this._name = name;\n }\n\n get name() {\n return this._name;\n }\n\n /**\n * 没有就注册,有就返回\n */\n register(eventName: string, eventProps?: EventProps) {\n if (this._events.has(eventName)) {\n return this._events.get(eventName) as Event;\n }\n\n this._events.set(\n eventName,\n new Event({\n ...(eventProps || {}),\n name: eventName,\n })\n );\n\n return this._events.get(eventName) as Event;\n }\n\n getEvent(eventName: string) {\n return this._events.get(eventName);\n }\n\n dispose() {\n if (this._disposed) return;\n for (const [_, event] of this._events) {\n event.dispose();\n }\n\n this._disposed = true;\n }\n}\n\nexport type IEvent = Event;\n","import Event from './Event';\n\nexport interface NodeEventEmitter {\n on(event: string | symbol, listener: Function): unknown;\n removeListener(event: string | symbol, listener: Function): unknown;\n}\n\n/**\n * Creates an {@link Event} from a node event emitter.\n */\nexport function fromNodeEvent(emitter: NodeEventEmitter, eventName: string) {\n // @ts-ignore\n const onFirstListenerAdd = () => emitter.on(eventName, fn);\n const onLastListenerRemove = () => emitter.removeListener(eventName, fn);\n const event = new Event({\n name: eventName,\n onWillAddFirstListener: onFirstListenerAdd,\n onDidRemoveLastListener: onLastListenerRemove,\n });\n\n const fn = (...args: any[]) => {\n return event.fire(...args);\n };\n\n return event.subscribe;\n}\n"],"names":["Event","props","name","onWillAddFirstListener","onDidAddFirstListener","onDidAddListener","onWillRemoveListener","onDidRemoveLastListener","coldTrigger","_coldTrigger","_onWillAddFirstListener","_onDidAddFirstListener","_onDidAddListener","_onWillRemoveListener","_onDidRemoveLastListener","subscribe","bind","_proto","prototype","listener","_listeners","length","_this$_onWillAddFirst","call","index","indexOf","console","error","_this$_onDidAddFirstL","_this$_onDidAddListen","push","_cacheCurrentValue","apply","toDisposable","_this","removeListener","_this$_onWillRemoveLi","splice","_this$_onDidRemoveLas","dispose","_this$_onDidRemoveLas2","fire","args","Array","_len","_key","arguments","_iterator","_createForOfIteratorHelperLoose","_step","done","value","Emitter","Map","_ref","_name","register","eventName","eventProps","_events","has","get","set","_extends","getEvent","_disposed","_step$value","_","event","_createClass","key","fromNodeEvent","emitter","onFirstListenerAdd","on","fn","onLastListenerRemove"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAGqBA,KAAK;EAmBxB,SAAAA,MAAYC,KAAoC;IAhBxC,eAAU,GAAoB,EAAE;IAiBtC,IACEC,IAAI,GAOFD,KAAK,CAPPC,IAAI;MACJC,sBAAsB,GAMpBF,KAAK,CANPE,sBAAsB;MACtBC,qBAAqB,GAKnBH,KAAK,CALPG,qBAAqB;MACrBC,gBAAgB,GAIdJ,KAAK,CAJPI,gBAAgB;MAChBC,oBAAoB,GAGlBL,KAAK,CAHPK,oBAAoB;MACpBC,uBAAuB,GAErBN,KAAK,CAFPM,uBAAuB;MACvBC,WAAW,GACTP,KAAK,CADPO,WAAW;IAGb,IAAI,CAACN,IAAI,GAAGA,IAAI;IAEhB,IAAI,CAACO,YAAY,GAAGD,WAAW;IAC/B,IAAI,CAACE,uBAAuB,GAAGP,sBAAsB;IACrD,IAAI,CAACQ,sBAAsB,GAAGP,qBAAqB;IACnD,IAAI,CAACQ,iBAAiB,GAAGP,gBAAgB;IACzC,IAAI,CAACQ,qBAAqB,GAAGP,oBAAoB;IACjD,IAAI,CAACQ,wBAAwB,GAAGP,uBAAuB;IACvD,IAAI,CAACQ,SAAS,GAAG,IAAI,CAACA,SAAS,CAACC,IAAI,CAAC,IAAI,CAAC;;EAC3C,IAAAC,MAAA,GAAAjB,KAAA,CAAAkB,SAAA;EAAAD,MAAA,CAEDF,SAAS,GAAT,SAAAA,UAAUI,QAAuB;;IAC/B,IAAI,CAAC,IA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EAAEuD,SAAS;IACftD,sBAAsB,EAAEsE,kBAAkB;IAC1ClE,uBAAuB,EAAEqE;GAC1B,CAAC;EAEF,IAAMD,EAAE,GAAG,SAALA,EAAEA;IACN,OAAOP,KAAK,CAAC3B,IAAI,CAAAT,KAAA,CAAVoC,KAAK,EAAAtB,SAAA,CAAc;GAC3B;EAED,OAAOsB,KAAK,CAACrD,SAAS;AACxB;;;;"}
@@ -0,0 +1,5 @@
1
+ export interface DomEventEmitter {
2
+ addEventListener(event: string | symbol, listener: Function): unknown;
3
+ removeEventListener(event: string | symbol, listener: Function): unknown;
4
+ }
5
+ export declare function fromDomEvent(emitter: DomEventEmitter, eventName: string): (listener: Function) => import("@x-oasis/disposable").IDisposable;
@@ -0,0 +1,5 @@
1
+ export interface NodeEventEmitter {
2
+ on(event: string | symbol, listener: Function): unknown;
3
+ removeListener(event: string | symbol, listener: Function): unknown;
4
+ }
5
+ export declare function fromNodeEvent(emitter: NodeEventEmitter, eventName: string): (listener: Function) => import("@x-oasis/disposable").IDisposable;
package/dist/index.d.ts CHANGED
@@ -1,9 +1,3 @@
1
- declare class Emitter {
2
- subscriptions: {
3
- [key: string]: any;
4
- };
5
- fire(event: any, ...rest: any[]): void;
6
- on(event: any, cb: any): () => void;
7
- off(event: any): void;
8
- }
9
- export default Emitter;
1
+ export { default as Emitter } from './Emitter';
2
+ export { fromNodeEvent } from './fromNodeEvent';
3
+ export { default as Event } from './Event';
@@ -0,0 +1,9 @@
1
+ export declare type EventProps = {
2
+ onWillAddFirstListener?: Function;
3
+ onDidAddFirstListener?: Function;
4
+ onDidAddListener?: Function;
5
+ onWillRemoveListener?: Function;
6
+ onDidRemoveLastListener?: Function;
7
+ coldTrigger?: boolean;
8
+ };
9
+ export declare type EventListener = Function;
@@ -0,0 +1 @@
1
+ export * from './event';
package/package.json CHANGED
@@ -1,20 +1,27 @@
1
1
  {
2
2
  "name": "@x-oasis/emitter",
3
- "version": "0.1.35",
4
- "description": "emitter function",
3
+ "version": "0.1.37",
4
+ "description": "each function",
5
5
  "main": "dist/index.js",
6
6
  "typings": "dist/index.d.ts",
7
- "module": "dist/emitter.esm.js",
7
+ "module": "dist/each.esm.js",
8
8
  "files": [
9
9
  "dist",
10
10
  "index.ts",
11
11
  "src"
12
12
  ],
13
+ "publishConfig": {
14
+ "access": "public"
15
+ },
13
16
  "author": "",
14
17
  "license": "ISC",
15
18
  "devDependencies": {
16
19
  "tsdx": "^0.14.1"
17
20
  },
21
+ "dependencies": {
22
+ "@x-oasis/is-object": "0.1.37",
23
+ "@x-oasis/disposable": "0.1.37"
24
+ },
18
25
  "scripts": {
19
26
  "build": "tsdx build --tsconfig tsconfig.build.json",
20
27
  "clean": "rimraf ./dist",
package/src/Emitter.ts ADDED
@@ -0,0 +1,53 @@
1
+ import Event from './Event';
2
+ import { EventProps } from './types';
3
+
4
+ export default class Emitter {
5
+ private _events = new Map<string, Event>();
6
+
7
+ private _disposed = false;
8
+
9
+ private _name: string;
10
+
11
+ constructor(props: { name: string }) {
12
+ const { name } = props || {};
13
+ this._name = name;
14
+ }
15
+
16
+ get name() {
17
+ return this._name;
18
+ }
19
+
20
+ /**
21
+ * 没有就注册,有就返回
22
+ */
23
+ register(eventName: string, eventProps?: EventProps) {
24
+ if (this._events.has(eventName)) {
25
+ return this._events.get(eventName) as Event;
26
+ }
27
+
28
+ this._events.set(
29
+ eventName,
30
+ new Event({
31
+ ...(eventProps || {}),
32
+ name: eventName,
33
+ })
34
+ );
35
+
36
+ return this._events.get(eventName) as Event;
37
+ }
38
+
39
+ getEvent(eventName: string) {
40
+ return this._events.get(eventName);
41
+ }
42
+
43
+ dispose() {
44
+ if (this._disposed) return;
45
+ for (const [_, event] of this._events) {
46
+ event.dispose();
47
+ }
48
+
49
+ this._disposed = true;
50
+ }
51
+ }
52
+
53
+ export type IEvent = Event;
package/src/Event.ts ADDED
@@ -0,0 +1,90 @@
1
+ import { toDisposable } from '@x-oasis/disposable';
2
+ import { EventListener, EventProps } from './types';
3
+
4
+ export default class Event {
5
+ readonly name: string;
6
+
7
+ private _listeners: EventListener[] = [];
8
+
9
+ private _onWillAddFirstListener?: Function;
10
+
11
+ private _onDidAddFirstListener?: Function;
12
+
13
+ private _onDidAddListener?: Function;
14
+
15
+ private _onWillRemoveListener?: Function;
16
+
17
+ private _onDidRemoveLastListener?: Function;
18
+
19
+ private _coldTrigger?: boolean;
20
+
21
+ private _cacheCurrentValue?: any[] | undefined;
22
+
23
+ constructor(props: EventProps & { name: string }) {
24
+ const {
25
+ name,
26
+ onWillAddFirstListener,
27
+ onDidAddFirstListener,
28
+ onDidAddListener,
29
+ onWillRemoveListener,
30
+ onDidRemoveLastListener,
31
+ coldTrigger,
32
+ } = props;
33
+
34
+ this.name = name;
35
+
36
+ this._coldTrigger = coldTrigger;
37
+ this._onWillAddFirstListener = onWillAddFirstListener;
38
+ this._onDidAddFirstListener = onDidAddFirstListener;
39
+ this._onDidAddListener = onDidAddListener;
40
+ this._onWillRemoveListener = onWillRemoveListener;
41
+ this._onDidRemoveLastListener = onDidRemoveLastListener;
42
+ this.subscribe = this.subscribe.bind(this);
43
+ }
44
+
45
+ subscribe(listener: EventListener) {
46
+ if (!this._listeners.length) {
47
+ this._onWillAddFirstListener?.();
48
+ }
49
+
50
+ const index = this._listeners.indexOf(listener);
51
+ if (index !== -1) {
52
+ console.error('add a duplicate listener');
53
+ } else {
54
+ this._listeners.push(listener);
55
+ if (this._listeners.length === 1) this._onDidAddFirstListener?.();
56
+ this._onDidAddListener?.();
57
+ if (this._coldTrigger && this._cacheCurrentValue)
58
+ listener(...this._cacheCurrentValue);
59
+ }
60
+
61
+ return toDisposable(() => {
62
+ this.removeListener(listener);
63
+ });
64
+ }
65
+
66
+ removeListener(listener: EventListener) {
67
+ const index = this._listeners.indexOf(listener);
68
+ if (index === -1) return;
69
+ this._onWillRemoveListener?.();
70
+
71
+ this._listeners.splice(index, 1);
72
+ if (!this._listeners.length) {
73
+ this._onDidRemoveLastListener?.();
74
+ }
75
+ }
76
+
77
+ dispose() {
78
+ this._listeners = [];
79
+ this._onDidRemoveLastListener?.();
80
+ }
81
+
82
+ fire(...args: any[]) {
83
+ if (this._coldTrigger) {
84
+ this._cacheCurrentValue = args;
85
+ }
86
+ for (const listener of this._listeners) {
87
+ listener(...args);
88
+ }
89
+ }
90
+ }
@@ -0,0 +1,26 @@
1
+ import Event from './Event';
2
+
3
+ export interface DomEventEmitter {
4
+ addEventListener(event: string | symbol, listener: Function): unknown;
5
+ removeEventListener(event: string | symbol, listener: Function): unknown;
6
+ }
7
+
8
+ /**
9
+ * Creates an {@link Event} from a window event emitter.
10
+ */
11
+ export function fromDomEvent(emitter: DomEventEmitter, eventName: string) {
12
+ // @ts-ignore
13
+ const onFirstListenerAdd = () => emitter.addEventListener(eventName, fn);
14
+ const onLastListenerRemove = () => emitter.removeEventListener(eventName, fn);
15
+ const event = new Event({
16
+ name: eventName,
17
+ onWillAddFirstListener: onFirstListenerAdd,
18
+ onDidRemoveLastListener: onLastListenerRemove,
19
+ });
20
+
21
+ const fn = (...args: any[]) => {
22
+ return event.fire(...args);
23
+ };
24
+
25
+ return event.subscribe;
26
+ }
@@ -0,0 +1,26 @@
1
+ import Event from './Event';
2
+
3
+ export interface NodeEventEmitter {
4
+ on(event: string | symbol, listener: Function): unknown;
5
+ removeListener(event: string | symbol, listener: Function): unknown;
6
+ }
7
+
8
+ /**
9
+ * Creates an {@link Event} from a node event emitter.
10
+ */
11
+ export function fromNodeEvent(emitter: NodeEventEmitter, eventName: string) {
12
+ // @ts-ignore
13
+ const onFirstListenerAdd = () => emitter.on(eventName, fn);
14
+ const onLastListenerRemove = () => emitter.removeListener(eventName, fn);
15
+ const event = new Event({
16
+ name: eventName,
17
+ onWillAddFirstListener: onFirstListenerAdd,
18
+ onDidRemoveLastListener: onLastListenerRemove,
19
+ });
20
+
21
+ const fn = (...args: any[]) => {
22
+ return event.fire(...args);
23
+ };
24
+
25
+ return event.subscribe;
26
+ }
package/src/index.ts CHANGED
@@ -1,29 +1,3 @@
1
- class Emitter {
2
- public subscriptions: {
3
- [key: string]: any;
4
- } = {};
5
-
6
- fire(event, ...rest) {
7
- const cbs = this.subscriptions[event] || [];
8
- for (let i = 0; i < cbs.length; i++) {
9
- cbs[i].apply(this, rest); // eslint-disable-line
10
- }
11
- }
12
-
13
- on(event, cb) {
14
- if (!this.subscriptions[event]) this.subscriptions[event] = [cb];
15
- else this.subscriptions[event].push(cb);
16
-
17
- return () => {
18
- const subscriptions = this.subscriptions[event];
19
- const index = subscriptions.indexOf(cb);
20
- if (index !== -1) subscriptions.splice(index, 1);
21
- };
22
- }
23
-
24
- off(event) {
25
- delete this.subscriptions[event];
26
- }
27
- }
28
-
29
- export default Emitter;
1
+ export { default as Emitter } from './Emitter';
2
+ export { fromNodeEvent } from './fromNodeEvent';
3
+ export { default as Event } from './Event';
@@ -0,0 +1,14 @@
1
+ export type EventProps = {
2
+ onWillAddFirstListener?: Function;
3
+ onDidAddFirstListener?: Function;
4
+
5
+ onDidAddListener?: Function;
6
+
7
+ onWillRemoveListener?: Function;
8
+
9
+ onDidRemoveLastListener?: Function;
10
+
11
+ coldTrigger?: boolean;
12
+ };
13
+
14
+ export type EventListener = Function;
@@ -0,0 +1 @@
1
+ export * from './event';