-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
EventGroup.ts
337 lines (290 loc) · 10.6 KB
/
EventGroup.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/* tslint:disable:no-string-literal */
import { assign } from './object';
/**
* EventRecord interface.
*
* @internal
*/
// tslint:disable:no-any
export interface IEventRecord {
target: any;
eventName: string;
parent: any;
callback: (args?: any) => void;
elementCallback?: (...args: any[]) => void;
objectCallback?: (args?: any) => void;
options?: boolean | AddEventListenerOptions;
}
// tslint:enable:no-any
/**
* EventRecordsByName interface.
*
* @internal
*/
export interface IEventRecordsByName {
[eventName: string]: IEventRecordList;
}
/**
* EventRecordList interface.
*
* @internal
*/
export interface IEventRecordList {
[id: string]: IEventRecord[] | number;
count: number;
}
/**
* DeclaredEventsByName interface.
*
* @internal
*/
export interface IDeclaredEventsByName {
[eventName: string]: boolean;
}
/** An instance of EventGroup allows anything with a handle to it to trigger events on it.
* If the target is an HTMLElement, the event will be attached to the element and can be
* triggered as usual (like clicking for onclick).
* The event can be triggered by calling EventGroup.raise() here. If the target is an
* HTMLElement, the event gets raised and is handled by the browser. Otherwise, it gets
* handled here in EventGroup, and the handler is called in the context of the parent
* (which is passed in in the constructor).
*
* @public
* {@docCategory EventGroup}
*/
export class EventGroup {
// tslint:disable-next-line:no-inferrable-types
private static _uniqueId: number = 0;
// tslint:disable-next-line:no-any
private _parent: any;
private _eventRecords: IEventRecord[];
private _id: number = EventGroup._uniqueId++;
private _isDisposed: boolean;
/** For IE8, bubbleEvent is ignored here and must be dealt with by the handler.
* Events raised here by default have bubbling set to false and cancelable set to true.
* This applies also to built-in events being raised manually here on HTMLElements,
* which may lead to unexpected behavior if it differs from the defaults.
*
*/
public static raise(
// tslint:disable-next-line:no-any
target: any,
eventName: string,
// tslint:disable-next-line:no-any
eventArgs?: any,
bubbleEvent?: boolean
): boolean | undefined {
let retVal;
if (EventGroup._isElement(target)) {
if (document.createEvent) {
let ev = document.createEvent('HTMLEvents');
ev.initEvent(eventName, bubbleEvent || false, true);
assign(ev, eventArgs);
retVal = target.dispatchEvent(ev);
// tslint:disable-next-line:no-any
} else if ((document as any)['createEventObject']) {
// IE8
// tslint:disable-next-line:no-any
let evObj = (document as any)['createEventObject'](eventArgs);
// cannot set cancelBubble on evObj, fireEvent will overwrite it
target.fireEvent('on' + eventName, evObj);
}
} else {
while (target && retVal !== false) {
let events = <IEventRecordsByName>target.__events__;
let eventRecords = events ? events[eventName] : null;
if (eventRecords) {
for (let id in eventRecords) {
if (eventRecords.hasOwnProperty(id)) {
let eventRecordList = <IEventRecord[]>eventRecords[id];
for (let listIndex = 0; retVal !== false && listIndex < eventRecordList.length; listIndex++) {
let record = eventRecordList[listIndex];
if (record.objectCallback) {
retVal = record.objectCallback.call(record.parent, eventArgs);
}
}
}
}
}
// If the target has a parent, bubble the event up.
target = bubbleEvent ? target.parent : null;
}
}
return retVal;
}
// tslint:disable-next-line:no-any
public static isObserved(target: any, eventName: string): boolean {
let events = target && <IEventRecordsByName>target.__events__;
return !!events && !!events[eventName];
}
/** Check to see if the target has declared support of the given event. */
// tslint:disable-next-line:no-any
public static isDeclared(target: any, eventName: string): boolean {
let declaredEvents = target && <IDeclaredEventsByName>target.__declaredEvents;
return !!declaredEvents && !!declaredEvents[eventName];
}
// tslint:disable-next-line:no-any
public static stopPropagation(event: any): void {
if (event.stopPropagation) {
event.stopPropagation();
} else {
// IE8
event.cancelBubble = true;
}
}
private static _isElement(target: HTMLElement): boolean {
return !!target && (!!target.addEventListener || (typeof HTMLElement !== 'undefined' && target instanceof HTMLElement));
}
/** parent: the context in which events attached to non-HTMLElements are called */
// tslint:disable-next-line:no-any
public constructor(parent: any) {
this._parent = parent;
this._eventRecords = [];
}
public dispose(): void {
if (!this._isDisposed) {
this._isDisposed = true;
this.off();
this._parent = null;
}
}
/** On the target, attach a set of events, where the events object is a name to function mapping. */
// tslint:disable-next-line:no-any
public onAll(target: any, events: { [key: string]: (args?: any) => void }, useCapture?: boolean): void {
for (let eventName in events) {
if (events.hasOwnProperty(eventName)) {
this.on(target, eventName, events[eventName], useCapture);
}
}
}
/** On the target, attach an event whose handler will be called in the context of the parent
* of this instance of EventGroup.
*/
// tslint:disable-next-line:no-any
public on(target: any, eventName: string, callback: (args?: any) => void, options?: boolean | AddEventListenerOptions): void {
if (eventName.indexOf(',') > -1) {
let events = eventName.split(/[ ,]+/);
for (let i = 0; i < events.length; i++) {
this.on(target, events[i], callback, options);
}
} else {
let parent = this._parent;
let eventRecord: IEventRecord = {
target: target,
eventName: eventName,
parent: parent,
callback: callback,
options
};
// Initialize and wire up the record on the target, so that it can call the callback if the event fires.
let events = <IEventRecordsByName>(target.__events__ = target.__events__ || {});
events[eventName] =
events[eventName] ||
<IEventRecordList>{
count: 0
};
events[eventName][this._id] = events[eventName][this._id] || [];
(<IEventRecord[]>events[eventName][this._id]).push(eventRecord);
events[eventName].count++;
if (EventGroup._isElement(target)) {
// tslint:disable-next-line:no-any
let processElementEvent = (...args: any[]) => {
if (this._isDisposed) {
return;
}
let result;
try {
result = callback.apply(parent, args);
if (result === false && args[0]) {
let e = args[0];
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
e.cancelBubble = true;
}
} catch (e) {
/* ErrorHelper.log(e); */
}
return result;
};
eventRecord.elementCallback = processElementEvent;
if (target.addEventListener) {
/* tslint:disable:ban-native-functions */
(<EventTarget>target).addEventListener(eventName, processElementEvent, options);
/* tslint:enable:ban-native-functions */
} else if (target.attachEvent) {
// IE8
target.attachEvent('on' + eventName, processElementEvent);
}
} else {
// tslint:disable-next-line:no-any
let processObjectEvent = (...args: any[]) => {
if (this._isDisposed) {
return;
}
return callback.apply(parent, args);
};
eventRecord.objectCallback = processObjectEvent;
}
// Remember the record locally, so that it can be removed.
this._eventRecords.push(eventRecord);
}
}
// tslint:disable-next-line:no-any
public off(target?: any, eventName?: string, callback?: (args?: any) => void, options?: boolean | AddEventListenerOptions): void {
for (let i = 0; i < this._eventRecords.length; i++) {
let eventRecord = this._eventRecords[i];
if (
(!target || target === eventRecord.target) &&
(!eventName || eventName === eventRecord.eventName) &&
(!callback || callback === eventRecord.callback) &&
(typeof options !== 'boolean' || options === eventRecord.options)
) {
let events = <IEventRecordsByName>eventRecord.target.__events__;
let targetArrayLookup = events[eventRecord.eventName];
let targetArray = targetArrayLookup ? <IEventRecord[]>targetArrayLookup[this._id] : null;
// We may have already target's entries, so check for null.
if (targetArray) {
if (targetArray.length === 1 || !callback) {
targetArrayLookup.count -= targetArray.length;
delete events[eventRecord.eventName][this._id];
} else {
targetArrayLookup.count--;
targetArray.splice(targetArray.indexOf(eventRecord), 1);
}
if (!targetArrayLookup.count) {
delete events[eventRecord.eventName];
}
}
if (eventRecord.elementCallback) {
if (eventRecord.target.removeEventListener) {
eventRecord.target.removeEventListener(eventRecord.eventName, eventRecord.elementCallback, eventRecord.options);
} else if (eventRecord.target.detachEvent) {
// IE8
eventRecord.target.detachEvent('on' + eventRecord.eventName, eventRecord.elementCallback);
}
}
this._eventRecords.splice(i--, 1);
}
}
}
/** Trigger the given event in the context of this instance of EventGroup. */
// tslint:disable-next-line:no-any
public raise(eventName: string, eventArgs?: any, bubbleEvent?: boolean): boolean | undefined {
return EventGroup.raise(this._parent, eventName, eventArgs, bubbleEvent);
}
/** Declare an event as being supported by this instance of EventGroup. */
public declare(event: string | string[]): void {
let declaredEvents = (this._parent.__declaredEvents = this._parent.__declaredEvents || {});
if (typeof event === 'string') {
declaredEvents[event] = true;
} else {
for (let i = 0; i < event.length; i++) {
declaredEvents[event[i]] = true;
}
}
}
}