-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
debounce-binding-behavior.js
59 lines (50 loc) · 1.89 KB
/
debounce-binding-behavior.js
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
var _dec, _class;
import { bindingMode, sourceContext, targetContext, bindingBehavior } from 'aurelia-binding';
const unset = {};
function debounceCallSource(event) {
const state = this.debounceState;
clearTimeout(state.timeoutId);
state.timeoutId = setTimeout(() => this.debouncedMethod(event), state.delay);
}
function debounceCall(context, newValue, oldValue) {
const state = this.debounceState;
clearTimeout(state.timeoutId);
if (context !== state.callContextToDebounce) {
state.oldValue = unset;
this.debouncedMethod(context, newValue, oldValue);
return;
}
if (state.oldValue === unset) {
state.oldValue = oldValue;
}
state.timeoutId = setTimeout(() => {
const _oldValue = state.oldValue;
state.oldValue = unset;
this.debouncedMethod(context, newValue, _oldValue);
}, state.delay);
}
export let DebounceBindingBehavior = (_dec = bindingBehavior('debounce'), _dec(_class = class DebounceBindingBehavior {
bind(binding, source, delay = 200) {
const isCallSource = binding.callSource !== undefined;
const methodToDebounce = isCallSource ? 'callSource' : 'call';
const debouncer = isCallSource ? debounceCallSource : debounceCall;
const mode = binding.mode;
const callContextToDebounce = mode === bindingMode.twoWay || mode === bindingMode.fromView ? targetContext : sourceContext;
binding.debouncedMethod = binding[methodToDebounce];
binding.debouncedMethod.originalName = methodToDebounce;
binding[methodToDebounce] = debouncer;
binding.debounceState = {
callContextToDebounce,
delay,
timeoutId: 0,
oldValue: unset
};
}
unbind(binding, source) {
const methodToRestore = binding.debouncedMethod.originalName;
binding[methodToRestore] = binding.debouncedMethod;
binding.debouncedMethod = null;
clearTimeout(binding.debounceState.timeoutId);
binding.debounceState = null;
}
}) || _class);