-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathcreateInputComponent.ts
74 lines (65 loc) · 1.57 KB
/
createInputComponent.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
import Vue, { CreateElement, RenderContext } from 'vue';
interface EventHandler {
[key: string]: (e: Event) => void;
}
type Callback = (value: Event | string) => void;
// Events to register handlers for
const events: string[] = [
'ionChange',
'ionInput',
'ionBlur',
'ionFocus',
'ionCancel',
'ionSelect'
];
export function createInputComponent(
name: string,
coreTag: string,
modelEvent = 'ionChange',
valueProperty = 'value'
) {
return Vue.extend({
name,
functional: true,
model: {
event: modelEvent,
prop: valueProperty
},
render(h: CreateElement, { data, listeners, slots }: RenderContext) {
return h(
coreTag,
{
...data,
on: buildEventHandlers(listeners, modelEvent, valueProperty)
},
slots().default
);
}
});
}
function buildEventHandlers(
listeners: RenderContext['listeners'],
modelEvent: string,
valueProperty: string
) {
const handlers: EventHandler = {};
// Loop through all the events
events.map((eventName: string) => {
if (!listeners[eventName]) {
return;
}
// Normalize listeners coming from context as Function | Function[]
const callbacks: Callback[] = Array.isArray(listeners[eventName])
? (listeners[eventName] as Callback[])
: [listeners[eventName] as Callback];
// Assign handlers
handlers[eventName] = (e: Event) => {
callbacks.map(f => {
if (e) {
f(modelEvent === eventName ? (e.target as any)[valueProperty] : e);
}
});
};
});
return handlers;
}