1 | import {bindingMode, bindingBehavior} from 'aurelia-binding';
|
2 |
|
3 | function throttle(newValue) {
|
4 | let state = this.throttleState;
|
5 | let elapsed = +new Date() - state.last;
|
6 | if (elapsed >= state.delay) {
|
7 | clearTimeout(state.timeoutId);
|
8 | state.timeoutId = null;
|
9 | state.last = +new Date();
|
10 | this.throttledMethod(newValue);
|
11 | return;
|
12 | }
|
13 | state.newValue = newValue;
|
14 | if (state.timeoutId === null) {
|
15 | state.timeoutId = setTimeout(
|
16 | () => {
|
17 | state.timeoutId = null;
|
18 | state.last = +new Date();
|
19 | this.throttledMethod(state.newValue);
|
20 | },
|
21 | state.delay - elapsed);
|
22 | }
|
23 | }
|
24 |
|
25 | @bindingBehavior('throttle')
|
26 | export class ThrottleBindingBehavior {
|
27 | bind(binding, source, delay = 200) {
|
28 |
|
29 | let methodToThrottle = 'updateTarget';
|
30 | if (binding.callSource) {
|
31 | methodToThrottle = 'callSource';
|
32 | } else if (binding.updateSource && binding.mode === bindingMode.twoWay) {
|
33 | methodToThrottle = 'updateSource';
|
34 | }
|
35 |
|
36 |
|
37 |
|
38 |
|
39 | binding.throttledMethod = binding[methodToThrottle];
|
40 | binding.throttledMethod.originalName = methodToThrottle;
|
41 |
|
42 |
|
43 | binding[methodToThrottle] = throttle;
|
44 |
|
45 |
|
46 | binding.throttleState = {
|
47 | delay: delay,
|
48 | last: 0,
|
49 | timeoutId: null
|
50 | };
|
51 | }
|
52 |
|
53 |
|
54 | unbind(binding, source) {
|
55 |
|
56 | let methodToRestore = binding.throttledMethod.originalName;
|
57 | binding[methodToRestore] = binding.throttledMethod;
|
58 | binding.throttledMethod = null;
|
59 | clearTimeout(binding.throttleState.timeoutId);
|
60 | binding.throttleState = null;
|
61 | }
|
62 | }
|