@whitesev/domutils 1.7.5 → 1.8.1

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.
package/dist/index.cjs.js CHANGED
@@ -115,47 +115,7 @@ const LAST_NUMBER_WEAK_MAP = new WeakMap();
115
115
  const cache = createCache(LAST_NUMBER_WEAK_MAP);
116
116
  const generateUniqueNumber = createGenerateUniqueNumber(cache, LAST_NUMBER_WEAK_MAP);
117
117
 
118
- const isMessagePort = (sender) => {
119
- return typeof sender.start === 'function';
120
- };
121
-
122
- const PORT_MAP = new WeakMap();
123
-
124
- const extendBrokerImplementation = (partialBrokerImplementation) => ({
125
- ...partialBrokerImplementation,
126
- connect: ({ call }) => {
127
- return async () => {
128
- const { port1, port2 } = new MessageChannel();
129
- const portId = await call('connect', { port: port1 }, [port1]);
130
- PORT_MAP.set(port2, portId);
131
- return port2;
132
- };
133
- },
134
- disconnect: ({ call }) => {
135
- return async (port) => {
136
- const portId = PORT_MAP.get(port);
137
- if (portId === undefined) {
138
- throw new Error('The given port is not connected.');
139
- }
140
- await call('disconnect', { portId });
141
- };
142
- },
143
- isSupported: ({ call }) => {
144
- return () => call('isSupported');
145
- }
146
- });
147
-
148
- const ONGOING_REQUESTS = new WeakMap();
149
- const createOrGetOngoingRequests = (sender) => {
150
- if (ONGOING_REQUESTS.has(sender)) {
151
- // @todo TypeScript needs to be convinced that has() works as expected.
152
- return ONGOING_REQUESTS.get(sender);
153
- }
154
- const ongoingRequests = new Map();
155
- ONGOING_REQUESTS.set(sender, ongoingRequests);
156
- return ongoingRequests;
157
- };
158
- const createBroker = (brokerImplementation) => {
118
+ const createBrokerFactory = (createOrGetOngoingRequests, extendBrokerImplementation, generateUniqueNumber, isMessagePort) => (brokerImplementation) => {
159
119
  const fullBrokerImplementation = extendBrokerImplementation(brokerImplementation);
160
120
  return (sender) => {
161
121
  const ongoingRequests = createOrGetOngoingRequests(sender);
@@ -198,81 +158,115 @@ const createBroker = (brokerImplementation) => {
198
158
  };
199
159
  };
200
160
 
201
- // Prefilling the Maps with a function indexed by zero is necessary to be compliant with the specification.
202
- const scheduledIntervalsState = new Map([[0, null]]); // tslint:disable-line no-empty
203
- const scheduledTimeoutsState = new Map([[0, null]]); // tslint:disable-line no-empty
204
- const wrap = createBroker({
205
- clearInterval: ({ call }) => {
206
- return (timerId) => {
207
- if (typeof scheduledIntervalsState.get(timerId) === 'symbol') {
208
- scheduledIntervalsState.set(timerId, null);
209
- call('clear', { timerId, timerType: 'interval' }).then(() => {
210
- scheduledIntervalsState.delete(timerId);
211
- });
212
- }
161
+ const createCreateOrGetOngoingRequests = (ongoingRequestsMap) => (sender) => {
162
+ if (ongoingRequestsMap.has(sender)) {
163
+ // @todo TypeScript needs to be convinced that has() works as expected.
164
+ return ongoingRequestsMap.get(sender);
165
+ }
166
+ const ongoingRequests = new Map();
167
+ ongoingRequestsMap.set(sender, ongoingRequests);
168
+ return ongoingRequests;
169
+ };
170
+
171
+ const createExtendBrokerImplementation = (portMap) => (partialBrokerImplementation) => ({
172
+ ...partialBrokerImplementation,
173
+ connect: ({ call }) => {
174
+ return async () => {
175
+ const { port1, port2 } = new MessageChannel();
176
+ const portId = await call('connect', { port: port1 }, [port1]);
177
+ portMap.set(port2, portId);
178
+ return port2;
213
179
  };
214
180
  },
215
- clearTimeout: ({ call }) => {
216
- return (timerId) => {
217
- if (typeof scheduledTimeoutsState.get(timerId) === 'symbol') {
218
- scheduledTimeoutsState.set(timerId, null);
219
- call('clear', { timerId, timerType: 'timeout' }).then(() => {
220
- scheduledTimeoutsState.delete(timerId);
221
- });
181
+ disconnect: ({ call }) => {
182
+ return async (port) => {
183
+ const portId = portMap.get(port);
184
+ if (portId === undefined) {
185
+ throw new Error('The given port is not connected.');
222
186
  }
187
+ await call('disconnect', { portId });
223
188
  };
224
189
  },
225
- setInterval: ({ call }) => {
226
- return (func, delay = 0, ...args) => {
227
- const symbol = Symbol();
228
- const timerId = generateUniqueNumber(scheduledIntervalsState);
229
- scheduledIntervalsState.set(timerId, symbol);
230
- const schedule = () => call('set', {
231
- delay,
232
- now: performance.timeOrigin + performance.now(),
233
- timerId,
234
- timerType: 'interval'
235
- }).then(() => {
236
- const state = scheduledIntervalsState.get(timerId);
237
- if (state === undefined) {
238
- throw new Error('The timer is in an undefined state.');
239
- }
240
- if (state === symbol) {
241
- func(...args);
242
- // Doublecheck if the interval should still be rescheduled because it could have been cleared inside of func().
243
- if (scheduledIntervalsState.get(timerId) === symbol) {
244
- schedule();
245
- }
246
- }
247
- });
248
- schedule();
249
- return timerId;
250
- };
251
- },
252
- setTimeout: ({ call }) => {
253
- return (func, delay = 0, ...args) => {
254
- const symbol = Symbol();
255
- const timerId = generateUniqueNumber(scheduledTimeoutsState);
256
- scheduledTimeoutsState.set(timerId, symbol);
257
- call('set', {
258
- delay,
259
- now: performance.timeOrigin + performance.now(),
260
- timerId,
261
- timerType: 'timeout'
262
- }).then(() => {
263
- const state = scheduledTimeoutsState.get(timerId);
264
- if (state === undefined) {
265
- throw new Error('The timer is in an undefined state.');
266
- }
267
- if (state === symbol) {
268
- // A timeout can be savely deleted because it is only called once.
269
- scheduledTimeoutsState.delete(timerId);
270
- func(...args);
271
- }
272
- });
273
- return timerId;
274
- };
190
+ isSupported: ({ call }) => {
191
+ return () => call('isSupported');
192
+ }
193
+ });
194
+
195
+ const isMessagePort = (sender) => {
196
+ return typeof sender.start === 'function';
197
+ };
198
+
199
+ const createBroker = createBrokerFactory(createCreateOrGetOngoingRequests(new WeakMap()), createExtendBrokerImplementation(new WeakMap()), generateUniqueNumber, isMessagePort);
200
+
201
+ const createClearIntervalFactory = (scheduledIntervalsState) => (clear) => (timerId) => {
202
+ if (typeof scheduledIntervalsState.get(timerId) === 'symbol') {
203
+ scheduledIntervalsState.set(timerId, null);
204
+ clear(timerId).then(() => {
205
+ scheduledIntervalsState.delete(timerId);
206
+ });
275
207
  }
208
+ };
209
+
210
+ const createClearTimeoutFactory = (scheduledTimeoutsState) => (clear) => (timerId) => {
211
+ if (typeof scheduledTimeoutsState.get(timerId) === 'symbol') {
212
+ scheduledTimeoutsState.set(timerId, null);
213
+ clear(timerId).then(() => {
214
+ scheduledTimeoutsState.delete(timerId);
215
+ });
216
+ }
217
+ };
218
+
219
+ const createSetIntervalFactory = (generateUniqueNumber, scheduledIntervalsState) => (set) => (func, delay = 0, ...args) => {
220
+ const symbol = Symbol();
221
+ const timerId = generateUniqueNumber(scheduledIntervalsState);
222
+ scheduledIntervalsState.set(timerId, symbol);
223
+ const schedule = () => set(delay, timerId).then(() => {
224
+ const state = scheduledIntervalsState.get(timerId);
225
+ if (state === undefined) {
226
+ throw new Error('The timer is in an undefined state.');
227
+ }
228
+ if (state === symbol) {
229
+ func(...args);
230
+ // Doublecheck if the interval should still be rescheduled because it could have been cleared inside of func().
231
+ if (scheduledIntervalsState.get(timerId) === symbol) {
232
+ schedule();
233
+ }
234
+ }
235
+ });
236
+ schedule();
237
+ return timerId;
238
+ };
239
+
240
+ const createSetTimeoutFactory = (generateUniqueNumber, scheduledTimeoutsState) => (set) => (func, delay = 0, ...args) => {
241
+ const symbol = Symbol();
242
+ const timerId = generateUniqueNumber(scheduledTimeoutsState);
243
+ scheduledTimeoutsState.set(timerId, symbol);
244
+ set(delay, timerId).then(() => {
245
+ const state = scheduledTimeoutsState.get(timerId);
246
+ if (state === undefined) {
247
+ throw new Error('The timer is in an undefined state.');
248
+ }
249
+ if (state === symbol) {
250
+ // A timeout can be savely deleted because it is only called once.
251
+ scheduledTimeoutsState.delete(timerId);
252
+ func(...args);
253
+ }
254
+ });
255
+ return timerId;
256
+ };
257
+
258
+ // Prefilling the Maps with a function indexed by zero is necessary to be compliant with the specification.
259
+ const scheduledIntervalsState = new Map([[0, null]]); // tslint:disable-line no-empty
260
+ const scheduledTimeoutsState = new Map([[0, null]]); // tslint:disable-line no-empty
261
+ const createClearInterval = createClearIntervalFactory(scheduledIntervalsState);
262
+ const createClearTimeout = createClearTimeoutFactory(scheduledTimeoutsState);
263
+ const createSetInterval = createSetIntervalFactory(generateUniqueNumber, scheduledIntervalsState);
264
+ const createSetTimeout = createSetTimeoutFactory(generateUniqueNumber, scheduledTimeoutsState);
265
+ const wrap = createBroker({
266
+ clearInterval: ({ call }) => createClearInterval((timerId) => call('clear', { timerId, timerType: 'interval' })),
267
+ clearTimeout: ({ call }) => createClearTimeout((timerId) => call('clear', { timerId, timerType: 'timeout' })),
268
+ setInterval: ({ call }) => createSetInterval((delay, timerId) => call('set', { delay, now: performance.timeOrigin + performance.now(), timerId, timerType: 'interval' })),
269
+ setTimeout: ({ call }) => createSetTimeout((delay, timerId) => call('set', { delay, now: performance.timeOrigin + performance.now(), timerId, timerType: 'timeout' }))
276
270
  });
277
271
  const load = (url) => {
278
272
  const worker = new Worker(url);
@@ -295,7 +289,7 @@ const createLoadOrReturnBroker = (loadBroker, worker) => {
295
289
  };
296
290
 
297
291
  // This is the minified and stringified code of the worker-timers-worker package.
298
- const worker = `(()=>{var e={455:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,s=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<s?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*s);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,u=r(i),c=a(u,i),l=t(c);e.addUniqueNumber=l,e.generateUniqueNumber=c}(t)}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,r),s.exports}(()=>{"use strict";const e=-32603,t=-32602,n=-32601,o=(e,t)=>Object.assign(new Error(e),{status:t}),s=t=>o('The handler of the method called "'.concat(t,'" returned an unexpected result.'),e),a=(t,r)=>async({data:{id:a,method:i,params:u}})=>{const c=r[i];try{if(void 0===c)throw(e=>o('The requested method called "'.concat(e,'" is not supported.'),n))(i);const r=void 0===u?c():c(u);if(void 0===r)throw(t=>o('The handler of the method called "'.concat(t,'" returned no required result.'),e))(i);const l=r instanceof Promise?await r:r;if(null===a){if(void 0!==l.result)throw s(i)}else{if(void 0===l.result)throw s(i);const{result:e,transferables:r=[]}=l;t.postMessage({id:a,result:e},r)}}catch(e){const{message:r,status:n=-32603}=e;t.postMessage({error:{code:n,message:r},id:a})}};var i=r(455);const u=new Map,c=(e,r,n)=>({...r,connect:({port:t})=>{t.start();const n=e(t,r),o=(0,i.generateUniqueNumber)(u);return u.set(o,()=>{n(),t.close(),u.delete(o)}),{result:o}},disconnect:({portId:e})=>{const r=u.get(e);if(void 0===r)throw(e=>o('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),t))(e);return r(),{result:null}},isSupported:async()=>{if(await new Promise(e=>{const t=new ArrayBuffer(0),{port1:r,port2:n}=new MessageChannel;r.onmessage=({data:t})=>e(null!==t),n.postMessage(t,[t])})){const e=n();return{result:e instanceof Promise?await e:e}}return{result:!1}}}),l=(e,t,r=()=>!0)=>{const n=c(l,t,r),o=a(e,n);return e.addEventListener("message",o),()=>e.removeEventListener("message",o)},d=(e,t)=>r=>{const n=t.get(r);if(void 0===n)return Promise.resolve(!1);const[o,s]=n;return e(o),t.delete(r),s(!1),Promise.resolve(!0)},f=(e,t,r,n)=>(o,s,a)=>{const i=o+s-t.timeOrigin,u=i-t.now();return new Promise(t=>{e.set(a,[r(n,u,i,e,t,a),t])})},m=new Map,h=d(globalThis.clearTimeout,m),p=new Map,v=d(globalThis.clearTimeout,p),w=((e,t)=>{const r=(n,o,s,a)=>{const i=n-e.now();i>0?o.set(a,[t(r,i,n,o,s,a),s]):(o.delete(a),s(!0))};return r})(performance,globalThis.setTimeout),g=f(m,performance,globalThis.setTimeout,w),T=f(p,performance,globalThis.setTimeout,w);l(self,{clear:async({timerId:e,timerType:t})=>({result:await("interval"===t?h(e):v(e))}),set:async({delay:e,now:t,timerId:r,timerType:n})=>({result:await("interval"===n?g:T)(e,t,r)})})})()})();`; // tslint:disable-line:max-line-length
292
+ const worker = `(()=>{var e={455(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,s=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<s?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*s);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,u=r(i),c=a(u,i),l=t(c);e.addUniqueNumber=l,e.generateUniqueNumber=c}(t)}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,r),s.exports}(()=>{"use strict";const e=-32603,t=-32602,n=-32601,o=(e,t)=>Object.assign(new Error(e),{status:t}),s=t=>o('The handler of the method called "'.concat(t,'" returned an unexpected result.'),e),a=(t,r)=>async({data:{id:a,method:i,params:u}})=>{const c=r[i];try{if(void 0===c)throw(e=>o('The requested method called "'.concat(e,'" is not supported.'),n))(i);const r=void 0===u?c():c(u);if(void 0===r)throw(t=>o('The handler of the method called "'.concat(t,'" returned no required result.'),e))(i);const l=r instanceof Promise?await r:r;if(null===a){if(void 0!==l.result)throw s(i)}else{if(void 0===l.result)throw s(i);const{result:e,transferables:r=[]}=l;t.postMessage({id:a,result:e},r)}}catch(e){const{message:r,status:n=-32603}=e;t.postMessage({error:{code:n,message:r},id:a})}};var i=r(455);const u=new Map,c=(e,r,n)=>({...r,connect:({port:t})=>{t.start();const n=e(t,r),o=(0,i.generateUniqueNumber)(u);return u.set(o,()=>{n(),t.close(),u.delete(o)}),{result:o}},disconnect:({portId:e})=>{const r=u.get(e);if(void 0===r)throw(e=>o('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),t))(e);return r(),{result:null}},isSupported:async()=>{if(await new Promise(e=>{const t=new ArrayBuffer(0),{port1:r,port2:n}=new MessageChannel;r.onmessage=({data:t})=>e(null!==t),n.postMessage(t,[t])})){const e=n();return{result:e instanceof Promise?await e:e}}return{result:!1}}}),l=(e,t,r=()=>!0)=>{const n=c(l,t,r),o=a(e,n);return e.addEventListener("message",o),()=>e.removeEventListener("message",o)},d=(e,t)=>r=>{const n=t.get(r);if(void 0===n)return Promise.resolve(!1);const[o,s]=n;return e(o),t.delete(r),s(!1),Promise.resolve(!0)},m=(e,t,r,n)=>(o,s,a)=>{const i=o+s-t.timeOrigin,u=i-t.now();return new Promise(t=>{e.set(a,[r(n,u,i,e,t,a),t])})},f=new Map,h=d(globalThis.clearTimeout,f),p=new Map,v=d(globalThis.clearTimeout,p),w=((e,t)=>{const r=(n,o,s,a)=>{const i=n-e.now();i>0?o.set(a,[t(r,i,n,o,s,a),s]):(o.delete(a),s(!0))};return r})(performance,globalThis.setTimeout),g=m(f,performance,globalThis.setTimeout,w),T=m(p,performance,globalThis.setTimeout,w);l(self,{clear:async({timerId:e,timerType:t})=>({result:await("interval"===t?h(e):v(e))}),set:async({delay:e,now:t,timerId:r,timerType:n})=>({result:await("interval"===n?g:T)(e,t,r)})})})()})();`; // tslint:disable-line:max-line-length
299
293
 
300
294
  const loadOrReturnBroker = createLoadOrReturnBroker(load, worker);
301
295
  const clearInterval$1 = (timerId) => loadOrReturnBroker().clearInterval(timerId);
@@ -523,13 +517,7 @@ const CommonUtils = {
523
517
  },
524
518
  };
525
519
 
526
- const version = "1.7.5";
527
-
528
- /* 数据 */
529
- const GlobalData = {
530
- /** .on添加在元素存储的事件 */
531
- domEventSymbol: Symbol("events_" + (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)),
532
- };
520
+ const version = "1.8.1";
533
521
 
534
522
  class ElementSelector {
535
523
  windowApi;
@@ -1622,6 +1610,12 @@ class ElementAnimate extends ElementWait {
1622
1610
  }
1623
1611
  new ElementAnimate();
1624
1612
 
1613
+ /* 数据 */
1614
+ const GlobalData = {
1615
+ /** .on添加在元素存储的事件 */
1616
+ domEventSymbol: Symbol("events_" + (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)),
1617
+ };
1618
+
1625
1619
  const OriginPrototype = {
1626
1620
  Object: {
1627
1621
  defineProperty: Object.defineProperty,
@@ -1681,7 +1675,7 @@ class ElementEvent extends ElementAnimate {
1681
1675
  if (element == null) {
1682
1676
  return {
1683
1677
  off() { },
1684
- trigger() { },
1678
+ emit() { },
1685
1679
  };
1686
1680
  }
1687
1681
  let $elList = [];
@@ -1816,10 +1810,10 @@ class ElementEvent extends ElementAnimate {
1816
1810
  /**
1817
1811
  * 主动触发事件
1818
1812
  * @param details 赋予触发的Event的额外属性,如果是Event类型,那么将自动代替默认new的Event对象
1819
- * @param useDispatchToTriggerEvent 是否使用dispatchEvent来触发事件,默认true,如果为false,则直接调用callback,但是这种会让使用了selectorTarget的没有值
1813
+ * @param useDispatchToEmit 是否使用dispatchEvent来触发事件,默认true,如果为false,则直接调用callback,但是这种会让使用了selectorTarget的没有值
1820
1814
  */
1821
- trigger: (details, useDispatchToTriggerEvent) => {
1822
- that.trigger($elList, eventTypeList, details, useDispatchToTriggerEvent);
1815
+ emit: (details, useDispatchToEmit) => {
1816
+ that.emit($elList, eventTypeList, details, useDispatchToEmit);
1823
1817
  },
1824
1818
  };
1825
1819
  }
@@ -1998,7 +1992,7 @@ class ElementEvent extends ElementAnimate {
1998
1992
  });
1999
1993
  });
2000
1994
  }
2001
- ready(...args) {
1995
+ onReady(...args) {
2002
1996
  const callback = args[0];
2003
1997
  // 异步回调
2004
1998
  let resolve = void 0;
@@ -2092,16 +2086,16 @@ class ElementEvent extends ElementAnimate {
2092
2086
  * @param element 需要触发的元素|元素数组|window
2093
2087
  * @param eventType 需要触发的事件
2094
2088
  * @param details 赋予触发的Event的额外属性,如果是Event类型,那么将自动代替默认new的Event对象
2095
- * @param useDispatchToTriggerEvent 是否使用dispatchEvent来触发事件,默认true,如果为false,则直接调用callback,但是这种会让使用了selectorTarget的没有值
2089
+ * @param useDispatchToEmit 是否使用dispatchEvent来触发事件,默认true,如果为false,则直接调用callback,但是这种会让使用了selectorTarget的没有值
2096
2090
  * @example
2097
2091
  * // 触发元素a.xx的click事件
2098
- * DOMUtils.trigger(document.querySelector("a.xx"),"click")
2099
- * DOMUtils.trigger("a.xx","click")
2092
+ * DOMUtils.emit(document.querySelector("a.xx"),"click")
2093
+ * DOMUtils.emit("a.xx","click")
2100
2094
  * // 触发元素a.xx的click、tap、hover事件
2101
- * DOMUtils.trigger(document.querySelector("a.xx"),"click tap hover")
2102
- * DOMUtils.trigger("a.xx",["click","tap","hover"])
2095
+ * DOMUtils.emit(document.querySelector("a.xx"),"click tap hover")
2096
+ * DOMUtils.emit("a.xx",["click","tap","hover"])
2103
2097
  */
2104
- trigger(element, eventType, details, useDispatchToTriggerEvent = true) {
2098
+ emit(element, eventType, details, useDispatchToEmit = true) {
2105
2099
  const that = this;
2106
2100
  if (typeof element === "string") {
2107
2101
  element = that.selectorAll(element);
@@ -2143,7 +2137,7 @@ class ElementEvent extends ElementAnimate {
2143
2137
  });
2144
2138
  }
2145
2139
  }
2146
- if (useDispatchToTriggerEvent == false && eventTypeItem in elementEvents) {
2140
+ if (useDispatchToEmit == false && eventTypeItem in elementEvents) {
2147
2141
  // 直接调用监听的事件
2148
2142
  elementEvents[eventTypeItem].forEach((eventsItem) => {
2149
2143
  eventsItem.callback(event);
@@ -2156,11 +2150,11 @@ class ElementEvent extends ElementAnimate {
2156
2150
  });
2157
2151
  }
2158
2152
  /**
2159
- * 绑定或触发元素的click事件
2153
+ * 监听或触发元素的click事件
2160
2154
  * @param element 目标元素
2161
2155
  * @param handler (可选)事件处理函数
2162
2156
  * @param details (可选)赋予触发的Event的额外属性
2163
- * @param useDispatchToTriggerEvent (可选)是否使用dispatchEvent来触发事件,默认true
2157
+ * @param useDispatchToEmit (可选)是否使用dispatchEvent来触发事件,默认true
2164
2158
  * @example
2165
2159
  * // 触发元素a.xx的click事件
2166
2160
  * DOMUtils.click(document.querySelector("a.xx"))
@@ -2169,7 +2163,7 @@ class ElementEvent extends ElementAnimate {
2169
2163
  * console.log("触发click事件成功")
2170
2164
  * })
2171
2165
  * */
2172
- click(element, handler, details, useDispatchToTriggerEvent) {
2166
+ click(element, handler, details, useDispatchToEmit) {
2173
2167
  const that = this;
2174
2168
  if (typeof element === "string") {
2175
2169
  element = that.selectorAll(element);
@@ -2180,23 +2174,23 @@ class ElementEvent extends ElementAnimate {
2180
2174
  if (CommonUtils.isNodeList(element)) {
2181
2175
  // 设置
2182
2176
  element.forEach(($ele) => {
2183
- that.click($ele, handler, details, useDispatchToTriggerEvent);
2177
+ that.click($ele, handler, details, useDispatchToEmit);
2184
2178
  });
2185
2179
  return;
2186
2180
  }
2187
2181
  if (handler == null) {
2188
- that.trigger(element, "click", details, useDispatchToTriggerEvent);
2182
+ that.emit(element, "click", details, useDispatchToEmit);
2189
2183
  }
2190
2184
  else {
2191
2185
  that.on(element, "click", null, handler);
2192
2186
  }
2193
2187
  }
2194
2188
  /**
2195
- * 绑定或触发元素的blur事件
2189
+ * 监听或触发元素的blur事件
2196
2190
  * @param element 目标元素
2197
2191
  * @param handler (可选)事件处理函数
2198
2192
  * @param details (可选)赋予触发的Event的额外属性
2199
- * @param useDispatchToTriggerEvent (可选)是否使用dispatchEvent来触发事件,默认true
2193
+ * @param useDispatchToEmit (可选)是否使用dispatchEvent来触发事件,默认true
2200
2194
  * @example
2201
2195
  * // 触发元素a.xx的blur事件
2202
2196
  * DOMUtils.blur(document.querySelector("a.xx"))
@@ -2205,7 +2199,7 @@ class ElementEvent extends ElementAnimate {
2205
2199
  * console.log("触发blur事件成功")
2206
2200
  * })
2207
2201
  * */
2208
- blur(element, handler, details, useDispatchToTriggerEvent) {
2202
+ blur(element, handler, details, useDispatchToEmit) {
2209
2203
  const that = this;
2210
2204
  if (typeof element === "string") {
2211
2205
  element = that.selectorAll(element);
@@ -2216,23 +2210,23 @@ class ElementEvent extends ElementAnimate {
2216
2210
  if (CommonUtils.isNodeList(element)) {
2217
2211
  // 设置
2218
2212
  element.forEach(($ele) => {
2219
- that.focus($ele, handler, details, useDispatchToTriggerEvent);
2213
+ that.focus($ele, handler, details, useDispatchToEmit);
2220
2214
  });
2221
2215
  return;
2222
2216
  }
2223
2217
  if (handler === null) {
2224
- that.trigger(element, "blur", details, useDispatchToTriggerEvent);
2218
+ that.emit(element, "blur", details, useDispatchToEmit);
2225
2219
  }
2226
2220
  else {
2227
2221
  that.on(element, "blur", null, handler);
2228
2222
  }
2229
2223
  }
2230
2224
  /**
2231
- * 绑定或触发元素的focus事件
2225
+ * 监听或触发元素的focus事件
2232
2226
  * @param element 目标元素
2233
2227
  * @param handler (可选)事件处理函数
2234
2228
  * @param details (可选)赋予触发的Event的额外属性
2235
- * @param useDispatchToTriggerEvent (可选)是否使用dispatchEvent来触发事件,默认true
2229
+ * @param useDispatchToEmit (可选)是否使用dispatchEvent来触发事件,默认true
2236
2230
  * @example
2237
2231
  * // 触发元素a.xx的focus事件
2238
2232
  * DOMUtils.focus(document.querySelector("a.xx"))
@@ -2241,7 +2235,7 @@ class ElementEvent extends ElementAnimate {
2241
2235
  * console.log("触发focus事件成功")
2242
2236
  * })
2243
2237
  * */
2244
- focus(element, handler, details, useDispatchToTriggerEvent) {
2238
+ focus(element, handler, details, useDispatchToEmit) {
2245
2239
  const that = this;
2246
2240
  if (typeof element === "string") {
2247
2241
  element = that.selectorAll(element);
@@ -2252,12 +2246,12 @@ class ElementEvent extends ElementAnimate {
2252
2246
  if (CommonUtils.isNodeList(element)) {
2253
2247
  // 设置
2254
2248
  element.forEach(($ele) => {
2255
- that.focus($ele, handler, details, useDispatchToTriggerEvent);
2249
+ that.focus($ele, handler, details, useDispatchToEmit);
2256
2250
  });
2257
2251
  return;
2258
2252
  }
2259
2253
  if (handler == null) {
2260
- that.trigger(element, "focus", details, useDispatchToTriggerEvent);
2254
+ that.emit(element, "focus", details, useDispatchToEmit);
2261
2255
  }
2262
2256
  else {
2263
2257
  that.on(element, "focus", null, handler);
@@ -2270,14 +2264,14 @@ class ElementEvent extends ElementAnimate {
2270
2264
  * @param option 配置
2271
2265
  * @example
2272
2266
  * // 监听a.xx元素的移入或移出
2273
- * DOMUtils.hover(document.querySelector("a.xx"),()=>{
2267
+ * DOMUtils.onHover(document.querySelector("a.xx"),()=>{
2274
2268
  * console.log("移入/移除");
2275
2269
  * })
2276
- * DOMUtils.hover("a.xx",()=>{
2270
+ * DOMUtils.onHover("a.xx",()=>{
2277
2271
  * console.log("移入/移除");
2278
2272
  * })
2279
2273
  */
2280
- hover(element, handler, option) {
2274
+ onHover(element, handler, option) {
2281
2275
  const that = this;
2282
2276
  if (typeof element === "string") {
2283
2277
  element = that.selectorAll(element);
@@ -2288,7 +2282,7 @@ class ElementEvent extends ElementAnimate {
2288
2282
  if (CommonUtils.isNodeList(element)) {
2289
2283
  // 设置
2290
2284
  element.forEach(($ele) => {
2291
- that.hover($ele, handler, option);
2285
+ that.onHover($ele, handler, option);
2292
2286
  });
2293
2287
  return;
2294
2288
  }
@@ -2296,12 +2290,12 @@ class ElementEvent extends ElementAnimate {
2296
2290
  that.on(element, "mouseleave", null, handler, option);
2297
2291
  }
2298
2292
  /**
2299
- * 当动画结束时触发事件
2293
+ * 监听动画结束
2300
2294
  * @param element 监听的元素
2301
2295
  * @param handler 触发的回调函数
2302
2296
  * @param option 配置项,这里默认配置once为true
2303
2297
  */
2304
- animationend(element, handler, option) {
2298
+ onAnimationend(element, handler, option) {
2305
2299
  const that = this;
2306
2300
  if (typeof element === "string") {
2307
2301
  element = that.selector(element);
@@ -2324,12 +2318,12 @@ class ElementEvent extends ElementAnimate {
2324
2318
  }
2325
2319
  }
2326
2320
  /**
2327
- * 当过渡结束时触发事件
2321
+ * 监听过渡结束
2328
2322
  * @param element 监听的元素
2329
2323
  * @param handler 触发的回调函数
2330
2324
  * @param option 配置项,这里默认配置once为true
2331
2325
  */
2332
- transitionend(element, handler, option) {
2326
+ onTransitionend(element, handler, option) {
2333
2327
  const that = this;
2334
2328
  if (typeof element === "string") {
2335
2329
  element = that.selector(element);
@@ -2366,7 +2360,7 @@ class ElementEvent extends ElementAnimate {
2366
2360
  * console.log("按键松开");
2367
2361
  * })
2368
2362
  */
2369
- keyup(element, handler, option) {
2363
+ onKeyup(element, handler, option) {
2370
2364
  const that = this;
2371
2365
  if (element == null) {
2372
2366
  return;
@@ -2377,7 +2371,7 @@ class ElementEvent extends ElementAnimate {
2377
2371
  if (CommonUtils.isNodeList(element)) {
2378
2372
  // 设置
2379
2373
  element.forEach(($ele) => {
2380
- that.keyup($ele, handler, option);
2374
+ that.onKeyup($ele, handler, option);
2381
2375
  });
2382
2376
  return;
2383
2377
  }
@@ -2398,7 +2392,7 @@ class ElementEvent extends ElementAnimate {
2398
2392
  * console.log("按键按下");
2399
2393
  * })
2400
2394
  */
2401
- keydown(element, handler, option) {
2395
+ onKeydown(element, handler, option) {
2402
2396
  const that = this;
2403
2397
  if (element == null) {
2404
2398
  return;
@@ -2409,7 +2403,7 @@ class ElementEvent extends ElementAnimate {
2409
2403
  if (CommonUtils.isNodeList(element)) {
2410
2404
  // 设置
2411
2405
  element.forEach(($ele) => {
2412
- that.keydown($ele, handler, option);
2406
+ that.onKeydown($ele, handler, option);
2413
2407
  });
2414
2408
  return;
2415
2409
  }
@@ -2430,7 +2424,7 @@ class ElementEvent extends ElementAnimate {
2430
2424
  * console.log("按键按下");
2431
2425
  * })
2432
2426
  */
2433
- keypress(element, handler, option) {
2427
+ onKeypress(element, handler, option) {
2434
2428
  const that = this;
2435
2429
  if (element == null) {
2436
2430
  return;
@@ -2441,76 +2435,76 @@ class ElementEvent extends ElementAnimate {
2441
2435
  if (CommonUtils.isNodeList(element)) {
2442
2436
  // 设置
2443
2437
  element.forEach(($ele) => {
2444
- that.keypress($ele, handler, option);
2438
+ that.onKeypress($ele, handler, option);
2445
2439
  });
2446
2440
  return;
2447
2441
  }
2448
2442
  that.on(element, "keypress", null, handler, option);
2449
2443
  }
2450
2444
  /**
2451
- * 监听某个元素键盘按键事件或window全局按键事件
2452
- * 按下有值的键时触发,按下Ctrl\Alt\Shift\Meta是无值键。按下先触发keydown事件,再触发keypress事件。
2453
- * @param element 需要监听的对象,可以是全局Window或者某个元素
2454
- * @param eventName 事件名,默认keypress
2455
- * @param callback 自己定义的回调事件,参数1为当前的key,参数2为组合按键,数组类型,包含ctrl、shift、alt和meta(win键或mac的cmd键)
2445
+ * 监听某个元素键盘按键事件或window全局按键事件
2446
+ * 按下有值的键时触发,按下Ctrl\Alt\Shift\Meta是无值键。按下先触发keydown事件,再触发keypress事件。
2447
+ * @param element 需要监听的对象,可以是全局Window或者某个元素
2448
+ * @param eventName 事件名,默认keypress,keydown - > keypress - > keyup
2449
+ * @param handler 自己定义的回调事件,参数1为当前的key,参数2为组合按键,数组类型,包含ctrl、shift、alt和meta(win键或mac的cmd键)
2456
2450
  * @param options 监听事件的配置
2457
- * @example
2458
- Utils.listenKeyboard(window,(keyName,keyValue,otherKey,event)=>{
2459
- if(keyName === "Enter"){
2460
- console.log("回车按键的值是:"+keyValue)
2461
- }
2462
- if(otherKey.indexOf("ctrl") && keyName === "Enter" ){
2463
- console.log("Ctrl和回车键");
2464
- }
2465
- })
2466
- * @example
2467
- 字母和数字键的键码值(keyCode)
2468
- 按键 键码 按键 键码 按键 键码 按键 键码
2469
- A 65 J 74 S 83 1 49
2470
- B 66 K 75 T 84 2 50
2471
- C 67 L 76 U 85 3 51
2472
- D 68 M 77 V 86 4 52
2473
- E 69 N 78 W 87 5 53
2474
- F 70 O 79 X 88 6 54
2475
- G 71 P 80 Y 89 7 55
2476
- H 72 Q 81 Z 90 8 56
2477
- I 73 R 82 0 48 9 57
2478
-
2479
- 数字键盘上的键的键码值(keyCode)
2480
- 功能键键码值(keyCode)
2481
- 按键 键码 按键 键码 按键 键码 按键 键码
2482
- 0 96 8 104 F1 112 F7 118
2483
- 1 97 9 105 F2 113 F8 119
2484
- 2 98 * 106 F3 114 F9 120
2485
- 3 99 + 107 F4 115 F10 121
2486
- 4 100 Enter 108 F5 116 F11 122
2487
- 5 101 - 109 F6 117 F12 123
2488
- 6 102 . 110
2489
- 7 103 / 111
2490
-
2491
- 控制键键码值(keyCode)
2492
- 按键 键码 按键 键码 按键 键码 按键 键码
2493
- BackSpace 8 Esc 27 → 39 -_ 189
2494
- Tab 9 Spacebar 32 ↓ 40 .> 190
2495
- Clear 12 Page Up 33 Insert 45 /? 191
2496
- Enter 13 Page Down 34 Delete 46 `~ 192
2497
- Shift 16 End 35 Num Lock 144 [{ 219
2498
- Control 17 Home 36 ;: 186 \| 220
2499
- Alt 18 ← 37 =+ 187 ]} 221
2500
- Cape Lock 20 ↑ 38 ,< 188 '" 222
2501
-
2502
- 多媒体键码值(keyCode)
2503
- 按键 键码
2504
- 音量加 175
2505
- 音量减 174
2506
- 停止 179
2507
- 静音 173
2508
- 浏览器 172
2509
- 邮件 180
2510
- 搜索 170
2511
- 收藏 171
2512
- **/
2513
- listenKeyboard(element, eventName = "keypress", callback, options) {
2451
+ * @example
2452
+ Utils.onKeyboard(window,(keyName,keyValue,otherKey,event)=>{
2453
+ if(keyName === "Enter"){
2454
+ console.log("回车按键的值是:"+keyValue)
2455
+ }
2456
+ if(otherKey.indexOf("ctrl") && keyName === "Enter" ){
2457
+ console.log("Ctrl和回车键");
2458
+ }
2459
+ })
2460
+ * @example
2461
+ 字母和数字键的键码值(keyCode)
2462
+ 按键 键码 按键 键码 按键 键码 按键 键码
2463
+ A 65 J 74 S 83 1 49
2464
+ B 66 K 75 T 84 2 50
2465
+ C 67 L 76 U 85 3 51
2466
+ D 68 M 77 V 86 4 52
2467
+ E 69 N 78 W 87 5 53
2468
+ F 70 O 79 X 88 6 54
2469
+ G 71 P 80 Y 89 7 55
2470
+ H 72 Q 81 Z 90 8 56
2471
+ I 73 R 82 0 48 9 57
2472
+
2473
+ 数字键盘上的键的键码值(keyCode)
2474
+ 功能键键码值(keyCode)
2475
+ 按键 键码 按键 键码 按键 键码 按键 键码
2476
+ 0 96 8 104 F1 112 F7 118
2477
+ 1 97 9 105 F2 113 F8 119
2478
+ 2 98 * 106 F3 114 F9 120
2479
+ 3 99 + 107 F4 115 F10 121
2480
+ 4 100 Enter 108 F5 116 F11 122
2481
+ 5 101 - 109 F6 117 F12 123
2482
+ 6 102 . 110
2483
+ 7 103 / 111
2484
+
2485
+ 控制键键码值(keyCode)
2486
+ 按键 键码 按键 键码 按键 键码 按键 键码
2487
+ BackSpace 8 Esc 27 → 39 -_ 189
2488
+ Tab 9 Spacebar 32 ↓ 40 .> 190
2489
+ Clear 12 Page Up 33 Insert 45 /? 191
2490
+ Enter 13 Page Down 34 Delete 46 `~ 192
2491
+ Shift 16 End 35 Num Lock 144 [{ 219
2492
+ Control 17 Home 36 ;: 186 \| 220
2493
+ Alt 18 ← 37 =+ 187 ]} 221
2494
+ Cape Lock 20 ↑ 38 ,< 188 '" 222
2495
+
2496
+ 多媒体键码值(keyCode)
2497
+ 按键 键码
2498
+ 音量加 175
2499
+ 音量减 174
2500
+ 停止 179
2501
+ 静音 173
2502
+ 浏览器 172
2503
+ 邮件 180
2504
+ 搜索 170
2505
+ 收藏 171
2506
+ **/
2507
+ onKeyboard(element, eventName = "keypress", handler, options) {
2514
2508
  const that = this;
2515
2509
  if (typeof element === "string") {
2516
2510
  element = that.selectorAll(element);
@@ -2534,8 +2528,8 @@ class ElementEvent extends ElementAnimate {
2534
2528
  if (event.shiftKey) {
2535
2529
  otherCodeList.push("shift");
2536
2530
  }
2537
- if (typeof callback === "function") {
2538
- callback(keyName, keyValue, otherCodeList, event);
2531
+ if (typeof handler === "function") {
2532
+ handler(keyName, keyValue, otherCodeList, event);
2539
2533
  }
2540
2534
  };
2541
2535
  that.on(element, eventName, keyboardEventCallBack, options);
@@ -2545,6 +2539,122 @@ class ElementEvent extends ElementAnimate {
2545
2539
  },
2546
2540
  };
2547
2541
  }
2542
+ /**
2543
+ * 监input、textarea的输入框值改变的事件(当输入法输入时,不会触发该监听)
2544
+ * @param $el 输入框元素
2545
+ * @param handler 回调函数
2546
+ * @param option 配置
2547
+ */
2548
+ onInput($el, handler, option) {
2549
+ /**
2550
+ * 是否正在输入中
2551
+ */
2552
+ let isComposite = false;
2553
+ const __callback = async (event) => {
2554
+ if (isComposite)
2555
+ return;
2556
+ await handler(event);
2557
+ };
2558
+ const __composition_start_callback = () => {
2559
+ isComposite = true;
2560
+ };
2561
+ const __composition_end_callback = () => {
2562
+ isComposite = false;
2563
+ this.emit($el, "input", {
2564
+ isComposite,
2565
+ });
2566
+ };
2567
+ const inputListener = this.on($el, "input", __callback, option);
2568
+ const compositionStartListener = this.on($el, "compositionstart", __composition_start_callback, option);
2569
+ const compositionEndListener = this.on($el, "compositionend", __composition_end_callback, option);
2570
+ return {
2571
+ off: () => {
2572
+ inputListener.off();
2573
+ compositionStartListener.off();
2574
+ compositionEndListener.off();
2575
+ },
2576
+ };
2577
+ }
2578
+ onDoubleClick(...args) {
2579
+ const $el = args[0];
2580
+ let selector = void 0;
2581
+ let handler;
2582
+ let options;
2583
+ if (args.length === 2) {
2584
+ if (typeof args[1] === "function") {
2585
+ handler = args[1];
2586
+ }
2587
+ else {
2588
+ throw new TypeError("handler is not a function");
2589
+ }
2590
+ }
2591
+ else if (args.length === 3) {
2592
+ if (typeof args[1] === "function") {
2593
+ handler = args[1];
2594
+ options = args[2];
2595
+ }
2596
+ else {
2597
+ selector = args[1];
2598
+ handler = args[2];
2599
+ }
2600
+ }
2601
+ else if (args.length === 4) {
2602
+ selector = args[1];
2603
+ handler = args[2];
2604
+ options = args[3];
2605
+ }
2606
+ else {
2607
+ throw new Error("args length error");
2608
+ }
2609
+ let $click = null;
2610
+ let isDoubleClick = false;
2611
+ let timer = void 0;
2612
+ /** 是否是移动端点击 */
2613
+ let isMobileTouch = false;
2614
+ const dblclick_handler = async (evt, option) => {
2615
+ if (evt.type === "dblclick" && isMobileTouch) {
2616
+ // 禁止在移动端触发dblclick事件
2617
+ return;
2618
+ }
2619
+ await handler(evt, option);
2620
+ };
2621
+ const dblClickListener = this.on($el, "dblclick", (evt) => {
2622
+ dblclick_handler(evt, {
2623
+ isDoubleClick: true,
2624
+ });
2625
+ }, options);
2626
+ const touchEndListener = this.on($el, "touchend", selector, (evt, selectorTarget) => {
2627
+ isMobileTouch = true;
2628
+ CommonUtils.clearTimeout(timer);
2629
+ timer = void 0;
2630
+ if (isDoubleClick && $click === selectorTarget) {
2631
+ isDoubleClick = false;
2632
+ $click = null;
2633
+ /* 判定为双击 */
2634
+ dblclick_handler(evt, {
2635
+ isDoubleClick: true,
2636
+ });
2637
+ }
2638
+ else {
2639
+ timer = CommonUtils.setTimeout(() => {
2640
+ isDoubleClick = false;
2641
+ // 判断为单击
2642
+ dblclick_handler(evt, {
2643
+ isDoubleClick: false,
2644
+ });
2645
+ }, 200);
2646
+ isDoubleClick = true;
2647
+ $click = selectorTarget;
2648
+ }
2649
+ }, options);
2650
+ return {
2651
+ off() {
2652
+ $click = null;
2653
+ dblClickListener.off();
2654
+ touchEndListener.off();
2655
+ },
2656
+ };
2657
+ }
2548
2658
  preventEvent(...args) {
2549
2659
  /**
2550
2660
  * 阻止事件的默认行为发生,并阻止事件传播