This repository has been archived by the owner on Mar 20, 2021. It is now read-only.
/
loading.js
410 lines (357 loc) · 11.3 KB
/
loading.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
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/*global collectionOptionNames, inheritVars */
var loadStart = 'load:start',
loadEnd = 'load:end',
rootObject;
Thorax.setRootObject = function(obj) {
rootObject = obj;
};
Thorax.loadHandler = function(start, end, context) {
var loadCounter = _.uniqueId();
return function(message, background, object) {
var self = context || this;
self._loadInfo = self._loadInfo || [];
var loadInfo = self._loadInfo[loadCounter];
function startLoadTimeout() {
clearTimeout(loadInfo.timeout);
loadInfo.timeout = setTimeout(function() {
try {
loadInfo.run = true;
start.call(self, loadInfo.message, loadInfo.background, loadInfo);
} catch (e) {
Thorax.onException('loadStart', e);
}
},
loadingTimeout * 1000);
}
if (!loadInfo) {
var loadingTimeout = self._loadingTimeoutDuration !== undefined ?
self._loadingTimeoutDuration : Thorax.View.prototype._loadingTimeoutDuration;
loadInfo = self._loadInfo[loadCounter] = _.extend({
events: [],
timeout: 0,
message: message,
background: !!background
}, Backbone.Events);
startLoadTimeout();
} else {
clearTimeout(loadInfo.endTimeout);
loadInfo.message = message;
if (!background && loadInfo.background) {
loadInfo.background = false;
startLoadTimeout();
}
}
loadInfo.events.push(object);
object.on(loadEnd, function endCallback() {
object.off(loadEnd, endCallback);
var loadingEndTimeout = self._loadingTimeoutEndDuration;
if (loadingEndTimeout === void 0) {
// If we are running on a non-view object pull the default timeout
loadingEndTimeout = Thorax.View.prototype._loadingTimeoutEndDuration;
}
var events = loadInfo.events,
index = events.indexOf(object);
if (index >= 0) {
events.splice(index, 1);
}
if (!events.length) {
loadInfo.endTimeout = setTimeout(function() {
try {
if (!events.length) {
var run = loadInfo.run;
if (run) {
// Emit the end behavior, but only if there is a paired start
end.call(self, loadInfo.background, loadInfo);
loadInfo.trigger(loadEnd, loadInfo);
}
// If stopping make sure we don't run a start
clearTimeout(loadInfo.timeout);
loadInfo = self._loadInfo[loadCounter] = undefined;
}
} catch (e) {
Thorax.onException('loadEnd', e);
}
}, loadingEndTimeout * 1000);
}
});
};
};
/**
* Helper method for propagating load:start events to other objects.
*
* Forwards load:start events that occur on `source` to `dest`.
*/
Thorax.forwardLoadEvents = function(source, dest, once) {
function load(message, backgound, object) {
if (once) {
source.off(loadStart, load);
}
dest.trigger(loadStart, message, backgound, object);
}
source.on(loadStart, load);
return {
off: function() {
source.off(loadStart, load);
}
};
};
//
// Data load event generation
//
/**
* Mixing for generating load:start and load:end events.
*/
Thorax.mixinLoadable = function(target, useParent) {
_.extend(target, {
//loading config
_loadingClassName: 'loading',
_loadingTimeoutDuration: 0.33,
_loadingTimeoutEndDuration: 0.10,
// Propagates loading view parameters to the AJAX layer
onLoadStart: function(message, background, object) {
var that = useParent ? this.parent : this;
if (!that.nonBlockingLoad && !background && rootObject && rootObject !== this) {
rootObject.trigger(loadStart, message, background, object);
}
$(that.el).addClass(that._loadingClassName);
//used by loading helpers
if (that._loadingCallbacks) {
_.each(that._loadingCallbacks, function(callback) {
callback();
});
}
},
onLoadEnd: function(/* background, object */) {
var that = useParent ? this.parent : this;
$(that.el).removeClass(that._loadingClassName);
//used by loading helpers
if (that._loadingCallbacks) {
_.each(that._loadingCallbacks, function(callback) {
callback();
});
}
}
});
};
Thorax.mixinLoadableEvents = function(target, useParent) {
_.extend(target, {
loadStart: function(message, background) {
var that = useParent ? this.parent : this;
that.trigger(loadStart, message, background, that);
},
loadEnd: function() {
var that = useParent ? this.parent : this;
that.trigger(loadEnd, that);
}
});
};
Thorax.mixinLoadable(Thorax.View.prototype);
Thorax.mixinLoadableEvents(Thorax.View.prototype);
Thorax.sync = function(method, dataObj, options) {
var self = this,
complete = options.complete;
options.complete = function() {
self._request = undefined;
self._aborted = false;
complete && complete.apply(this, arguments);
};
this._request = Backbone.sync.apply(this, arguments);
return this._request;
};
function bindToRoute(callback, failback) {
var fragment = Backbone.history.getFragment(),
routeChanged = false;
function routeHandler() {
if (fragment === Backbone.history.getFragment()) {
return;
}
routeChanged = true;
res.cancel();
failback && failback();
}
Backbone.history.on('route', routeHandler);
function finalizer() {
Backbone.history.off('route', routeHandler);
var args = Array.prototype.slice.call(arguments, 1);
if (!routeChanged) {
callback.apply(this, args);
}
}
var res = _.bind(finalizer, this);
res.cancel = function() {
Backbone.history.off('route', routeHandler);
};
return res;
}
function loadData(callback, failback, options) {
if (this.isPopulated()) {
return callback(this);
}
if (arguments.length === 2 && typeof failback !== 'function' && _.isObject(failback)) {
options = failback;
failback = false;
}
var self = this,
routeChanged = false,
successCallback = bindToRoute(_.bind(callback, self), function() {
routeChanged = true;
if (self._request) {
self._aborted = true;
self._request.abort();
}
failback && failback.call(self, false);
});
this.fetch(_.defaults({
success: successCallback,
error: failback && function() {
if (!routeChanged) {
failback.apply(self, [true].concat(_.toArray(arguments)));
}
},
complete: function() {
successCallback.cancel();
}
}, options));
}
function fetchQueue(options, $super) {
if (options.resetQueue) {
// WARN: Should ensure that loaders are protected from out of band data
// when using this option
this.fetchQueue = undefined;
}
if (!this.fetchQueue) {
// Kick off the request
this.fetchQueue = [options];
options = _.defaults({
success: flushQueue(this, this.fetchQueue, 'success'),
error: flushQueue(this, this.fetchQueue, 'error'),
complete: flushQueue(this, this.fetchQueue, 'complete')
}, options);
$super.call(this, options);
} else {
// Currently fetching. Queue and process once complete
this.fetchQueue.push(options);
}
}
function flushQueue(self, fetchQueue, handler) {
return function() {
var args = arguments;
// Flush the queue. Executes any callback handlers that
// may have been passed in the fetch options.
_.each(fetchQueue, function(options) {
if (options[handler]) {
options[handler].apply(this, args);
}
}, this);
// Reset the queue if we are still the active request
if (self.fetchQueue === fetchQueue) {
self.fetchQueue = undefined;
}
};
}
var klasses = [];
Thorax.Model && klasses.push(Thorax.Model);
Thorax.Collection && klasses.push(Thorax.Collection);
_.each(klasses, function(DataClass) {
var $fetch = DataClass.prototype.fetch;
Thorax.mixinLoadableEvents(DataClass.prototype, false);
_.extend(DataClass.prototype, {
sync: Thorax.sync,
fetch: function(options) {
options = options || {};
var self = this,
complete = options.complete;
options.complete = function() {
complete && complete.apply(this, arguments);
self.loadEnd();
};
self.loadStart(undefined, options.background);
return fetchQueue.call(this, options || {}, $fetch);
},
load: function(callback, failback, options) {
if (arguments.length === 2 && typeof failback !== 'function') {
options = failback;
failback = false;
}
options = options || {};
if (!options.background && !this.isPopulated() && rootObject) {
// Make sure that the global scope sees the proper load events here
// if we are loading in standalone mode
Thorax.forwardLoadEvents(this, rootObject, true);
}
loadData.call(this, callback, failback, options);
}
});
});
Thorax.Util.bindToRoute = bindToRoute;
if (Thorax.Router) {
Thorax.Router.bindToRoute = Thorax.Router.prototype.bindToRoute = bindToRoute;
}
// Propagates loading view parameters to the AJAX layer
Thorax.View.prototype._modifyDataObjectOptions = function(dataObject, options) {
options.ignoreErrors = this.ignoreFetchError;
options.background = this.nonBlockingLoad;
return options;
};
inheritVars.collection.loading = function() {
var loadingView = this.loadingView,
loadingTemplate = this.loadingTemplate,
loadingPlacement = this.loadingPlacement;
//add "loading-view" and "loading-template" options to collection helper
if (loadingView || loadingTemplate) {
var callback = Thorax.loadHandler(_.bind(function() {
var item;
if (this.collection.length === 0) {
this.$el.empty();
}
if (loadingView) {
var instance = Thorax.Util.getViewInstance(loadingView, {
collection: this.collection
});
this._addChild(instance);
if (loadingTemplate) {
instance.render(loadingTemplate);
} else {
instance.render();
}
item = instance;
} else {
item = this.renderTemplate(loadingTemplate);
}
var index = loadingPlacement
? loadingPlacement.call(this)
: this.collection.length
;
this.appendItem(item, index);
this.$el.children().eq(index).attr('data-loading-element', this.collection.cid);
}, this), _.bind(function() {
this.$el.find('[data-loading-element="' + this.collection.cid + '"]').remove();
}, this),
this.collection);
this.listenTo(this.collection, 'load:start', callback);
}
};
if (typeof collectionOptionNames !== 'undefined') {
collectionOptionNames['loading-template'] = 'loadingTemplate';
collectionOptionNames['loading-view'] = 'loadingView';
collectionOptionNames['loading-placement'] = 'loadingPlacement';
}
Thorax.View.on({
'load:start': Thorax.loadHandler(
function(message, background, object) {
this.onLoadStart(message, background, object);
},
function(background, object) {
this.onLoadEnd(object);
}),
collection: {
'load:start': function(message, background, object) {
this.trigger(loadStart, message, background, object);
}
},
model: {
'load:start': function(message, background, object) {
this.trigger(loadStart, message, background, object);
}
}
});