-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
on.ts
373 lines (303 loc) · 11.2 KB
/
on.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import { assert } from '@ember/debug';
import { DEBUG } from '@glimmer/env';
import { CapturedArguments, Destroyable, ModifierManager, VMArguments } from '@glimmer/interfaces';
import { CONSTANT_TAG, Tag } from '@glimmer/validator';
import { SimpleElement } from '@simple-dom/interface';
import buildUntouchableThis from '../utils/untouchable-this';
const untouchableContext = buildUntouchableThis('`on` modifier');
/**
@module ember
*/
/*
Internet Explorer 11 does not support `once` and also does not support
passing `eventOptions`. In some situations it then throws a weird script
error, like:
```
Could not complete the operation due to error 80020101
```
This flag determines, whether `{ once: true }` and thus also event options in
general are supported.
*/
const SUPPORTS_EVENT_OPTIONS = (() => {
try {
const div = document.createElement('div');
let counter = 0;
div.addEventListener('click', () => counter++, { once: true });
let event;
if (typeof Event === 'function') {
event = new Event('click');
} else {
event = document.createEvent('Event');
event.initEvent('click', true, true);
}
div.dispatchEvent(event);
div.dispatchEvent(event);
return counter === 1;
} catch (error) {
return false;
}
})();
export class OnModifierState {
public tag: Tag;
public element: Element;
public args: CapturedArguments;
public eventName!: string;
public callback!: EventListener;
private userProvidedCallback!: EventListener;
public once?: boolean;
public passive?: boolean;
public capture?: boolean;
public options?: AddEventListenerOptions;
public shouldUpdate = true;
constructor(element: Element, args: CapturedArguments) {
this.element = element;
this.args = args;
this.tag = args.tag;
}
updateFromArgs() {
let { args } = this;
let { once, passive, capture }: AddEventListenerOptions = args.named.value();
if (once !== this.once) {
this.once = once;
this.shouldUpdate = true;
}
if (passive !== this.passive) {
this.passive = passive;
this.shouldUpdate = true;
}
if (capture !== this.capture) {
this.capture = capture;
this.shouldUpdate = true;
}
let options: AddEventListenerOptions;
if (once || passive || capture) {
options = this.options = { once, passive, capture };
} else {
this.options = undefined;
}
assert(
'You must pass a valid DOM event name as the first argument to the `on` modifier',
args.positional.at(0) !== undefined && typeof args.positional.at(0).value() === 'string'
);
let eventName = args.positional.at(0).value() as string;
if (eventName !== this.eventName) {
this.eventName = eventName;
this.shouldUpdate = true;
}
assert(
'You must pass a function as the second argument to the `on` modifier',
args.positional.at(1) !== undefined && typeof args.positional.at(1).value() === 'function'
);
let userProvidedCallback = args.positional.at(1).value() as EventListener;
if (userProvidedCallback !== this.userProvidedCallback) {
this.userProvidedCallback = userProvidedCallback;
this.shouldUpdate = true;
}
assert(
`You can only pass two positional arguments (event name and callback) to the \`on\` modifier, but you provided ${args.positional.length}. Consider using the \`fn\` helper to provide additional arguments to the \`on\` callback.`,
args.positional.length === 2
);
let needsCustomCallback =
(SUPPORTS_EVENT_OPTIONS === false && once) /* needs manual once implementation */ ||
(DEBUG && passive) /* needs passive enforcement */;
if (this.shouldUpdate) {
if (needsCustomCallback) {
let callback = (this.callback = function(this: Element, event) {
if (DEBUG && passive) {
event.preventDefault = () => {
assert(
`You marked this listener as 'passive', meaning that you must not call 'event.preventDefault()': \n\n${userProvidedCallback}`
);
};
}
if (!SUPPORTS_EVENT_OPTIONS && once) {
removeEventListener(this, eventName, callback, options);
}
return userProvidedCallback.call(untouchableContext, event);
});
} else if (DEBUG) {
// prevent the callback from being bound to the element
this.callback = userProvidedCallback.bind(untouchableContext);
} else {
this.callback = userProvidedCallback;
}
}
}
destroy() {
let { element, eventName, callback, options } = this;
removeEventListener(element, eventName, callback, options);
}
}
let adds = 0;
let removes = 0;
function removeEventListener(
element: Element,
eventName: string,
callback: EventListener,
options?: AddEventListenerOptions
): void {
removes++;
if (SUPPORTS_EVENT_OPTIONS) {
// when options are supported, use them across the board
element.removeEventListener(eventName, callback, options);
} else if (options !== undefined && options.capture) {
// used only in the following case:
//
// `{ once: true | false, passive: true | false, capture: true }
//
// `once` is handled via a custom callback that removes after first
// invocation so we only care about capture here as a boolean
element.removeEventListener(eventName, callback, true);
} else {
// used only in the following cases:
//
// * where there is no options
// * `{ once: true | false, passive: true | false, capture: false }
element.removeEventListener(eventName, callback);
}
}
function addEventListener(
element: Element,
eventName: string,
callback: EventListener,
options?: AddEventListenerOptions
): void {
adds++;
if (SUPPORTS_EVENT_OPTIONS) {
// when options are supported, use them across the board
element.addEventListener(eventName, callback, options);
} else if (options !== undefined && options.capture) {
// used only in the following case:
//
// `{ once: true | false, passive: true | false, capture: true }
//
// `once` is handled via a custom callback that removes after first
// invocation so we only care about capture here as a boolean
element.addEventListener(eventName, callback, true);
} else {
// used only in the following cases:
//
// * where there is no options
// * `{ once: true | false, passive: true | false, capture: false }
element.addEventListener(eventName, callback);
}
}
/**
The `{{on}}` modifier lets you easily add event listeners (it uses
[EventTarget.addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)
internally).
For example, if you'd like to run a function on your component when a `<button>`
in the components template is clicked you might do something like:
```app/components/like-post.hbs
<button {{on 'click' this.saveLike}}>Like this post!</button>
```
```app/components/like-post.js
import Component from '@glimmer/component';
import { action } from '@ember/object';
export default class LikePostComponent extends Component {
@action
saveLike() {
// someone likes your post!
// better send a request off to your server...
}
}
```
### Arguments
`{{on}}` accepts two positional arguments, and a few named arguments.
The positional arguments are:
- `event` -- the name to use when calling `addEventListener`
- `callback` -- the function to be passed to `addEventListener`
The named arguments are:
- capture -- a `true` value indicates that events of this type will be dispatched
to the registered listener before being dispatched to any EventTarget beneath it
in the DOM tree.
- once -- indicates that the listener should be invoked at most once after being
added. If true, the listener would be automatically removed when invoked.
- passive -- if `true`, indicates that the function specified by listener will never
call preventDefault(). If a passive listener does call preventDefault(), the user
agent will do nothing other than generate a console warning. See
[Improving scrolling performance with passive listeners](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Improving_scrolling_performance_with_passive_listeners)
to learn more.
The callback function passed to `{{on}}` will receive any arguments that are passed
to the event handler. Most commonly this would be the `event` itself.
If you would like to pass additional arguments to the function you should use
the `{{fn}}` helper.
For example, in our example case above if you'd like to pass in the post that
was being liked when the button is clicked you could do something like:
```app/components/like-post.hbs
<button {{on 'click' (fn this.saveLike @post)}}>Like this post!</button>
```
In this case, the `saveLike` function will receive two arguments: the click event
and the value of `@post`.
### Function Context
In the example above, we used `@action` to ensure that `likePost` is
properly bound to the `items-list`, but let's explore what happens if we
left out `@action`:
```app/components/like-post.js
import Component from '@glimmer/component';
export default class LikePostComponent extends Component {
saveLike() {
// ...snip...
}
}
```
In this example, when the button is clicked `saveLike` will be invoked,
it will **not** have access to the component instance. In other
words, it will have no `this` context, so please make sure your functions
are bound (via `@action` or other means) before passing into `on`!
@method on
@for Ember.Templates.helpers
@public
@since 3.11.0
*/
export default class OnModifierManager implements ModifierManager<OnModifierState | null, unknown> {
public SUPPORTS_EVENT_OPTIONS: boolean = SUPPORTS_EVENT_OPTIONS;
public isInteractive: boolean;
constructor(isInteractive: boolean) {
this.isInteractive = isInteractive;
}
get counters() {
return { adds, removes };
}
create(element: SimpleElement | Element, _state: unknown, args: VMArguments) {
if (!this.isInteractive) {
return null;
}
const capturedArgs = args.capture();
return new OnModifierState(<Element>element, capturedArgs);
}
getTag(state: OnModifierState | null): Tag {
if (state === null) {
return CONSTANT_TAG;
}
return state.tag;
}
install(state: OnModifierState | null) {
if (state === null) {
return;
}
state.updateFromArgs();
let { element, eventName, callback, options } = state;
addEventListener(element, eventName, callback, options);
state.shouldUpdate = false;
}
update(state: OnModifierState | null) {
if (state === null) {
return;
}
// stash prior state for el.removeEventListener
let { element, eventName, callback, options } = state;
state.updateFromArgs();
if (!state.shouldUpdate) {
return;
}
// use prior state values for removal
removeEventListener(element, eventName, callback, options);
// read updated values from the state object
addEventListener(state.element, state.eventName, state.callback, state.options);
state.shouldUpdate = false;
}
getDestructor(state: Destroyable | null) {
return state;
}
}