-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcuba-data-loading-behavior.html
More file actions
121 lines (113 loc) · 2.91 KB
/
cuba-data-loading-behavior.html
File metadata and controls
121 lines (113 loc) · 2.91 KB
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
<script>
/**
* In order to use this behavior:
* 1. _load method should be overridden. It must return jqXHR promise.
* 2. Call _optionsChanged method on meaningful properties changes/initialization i.e:
*
* `observers: ['_optionsChanged(serviceName, method, handleAs, auto)']`
*
* @polymerBehavior CubaDataLoadingBehavior
**/
CubaDataLoadingBehavior = {
/**
* Fired when data loading started.
*
* @event cuba-data-loading-start
*/
/**
* Fired when data loading finished.
*
* @event cuba-data-loading-finish
*/
/**
* Fired when data loading failed.
*
* @event cuba-data-loading-error
*/
properties: {
/**
* If true - automatically loads data.
*/
auto: {
type: Object,
value: true
},
/**
* Loaded data
*/
data: {
notify: true,
readOnly: true
},
/**
* Amount of time (in milliseconds) to send a request after property change (to prevent frequent requests).
*/
debounceDuration: {
type: Number,
value: 0
},
/**
* Indicates whether last request is pending.
*/
loading: {
type: Boolean,
notify: true,
readOnly: true
}
},
/**
* Loads data.
* Returns Promise.
*/
load: function(abortable) {
return new Promise(function(resolve, reject) {
this.debounce('loading', function() {
var fetchOptions = this._handleAbortable(abortable);
this.loadRequest = this._load(fetchOptions);
if (!this.loadRequest) {
return;
}
this._setLoading(true);
this.fire("cuba-data-loading-start");
this.loadRequest.then(
function(data) {
this._setLoading(false);
this._setData(data);
this.fire("cuba-data-loading-finish");
resolve(data);
}.bind(this),
function(error) {
this._setLoading(false);
this.fire("cuba-data-loading-error");
reject({message: 'Failed to load data', errorData: error || null});
}.bind(this)
);
}, this.debounceDuration);
}.bind(this));
},
_optionsChanged: function() {
if (this.auto) {
this.load(true);
}
},
_handleAbortable: function (abortable) {
var options = {};
if ('AbortController' in window) {
if (this.controller) {
this.controller.abort();
}
if (abortable) {
this.controller = new AbortController();
options.signal = this.controller.signal;
}
}
return options;
},
/**
* This method has to be overridden to contain real loading logic.
*/
_load: function() {
throw new Error('Missing data loading implementation')
}
}
</script>