-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathpaging-collection.js
More file actions
495 lines (455 loc) · 18.8 KB
/
paging-collection.js
File metadata and controls
495 lines (455 loc) · 18.8 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
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
/**
* A generic server paging collection.
*
* By default this collection is designed to work with Django Rest
* Framework APIs, but can be configured to work with others. There is
* support for ascending or descending sort on a particular field, as
* well as filtering on a field. While the backend API may use either
* zero or one indexed page numbers, this collection uniformly exposes a
* one indexed interface to make consumption easier for views.
*
* Subclasses may want to override the following properties:
*
* - url (`string`): The base URL for the API endpoint.
* - state (`object`): Object to overrride default state values
* provided to `Backbone.paginator`.
* - queryParams (`object`): Specifies Query parameters for the API
* call using the `Backbone.paginator` API. In the case of built-
* in `Backbone.paginator` state keys, this maps those state keys
* to query parameter keys. queryParams can also map query
* parameter keys to functions providing values for such keys.
* Subclasses may add entries as necessary. By default,
* `'sort_order'` is the query parameter used for sorting, with
* values of `'asc'` for increasing sort and `'desc'` for decreasing
* sort.
*
* @module PagingCollection
*/
(function(define) {
'use strict';
define(['jquery', 'underscore', 'backbone.paginator'], function($, _, PageableCollection) {
var PagingCollection = PageableCollection.extend({
mode: 'server',
isStale: false,
sortableFields: {},
filterableFields: {},
state: {
firstPage: 1,
pageSize: 10,
sortKey: null
},
queryParams: {
currentPage: 'page',
pageSize: 'page_size',
totalRecords: 'count',
totalPages: 'num_pages',
sortKey: 'order_by',
order: 'sort_order'
},
constructor: function(models, options) {
this.state = _.extend({}, PagingCollection.prototype.state, this.state);
this.queryParams = _.extend({}, PagingCollection.prototype.queryParams, this.queryParams);
PageableCollection.prototype.constructor.call(this, models, options);
},
initialize: function(models, options) {
// These must be initialized in the constructor
// because otherwise all PagingCollections would point
// to the same object references for sortableFields
// and filterableFields.
this.sortableFields = {};
this.filterableFields = {};
PageableCollection.prototype.initialize.call(this, models, options);
},
parse: function(response, options) {
// PageableCollection expects the response to be an
// array of two elements - the server-side state
// metadata (page, size, etc.), and the array of
// objects.
var modifiedResponse = [];
modifiedResponse.push(_.omit(response, 'results'));
modifiedResponse.push(response.results);
return PageableCollection.prototype.parse.call(this, modifiedResponse, options);
},
/**
* Returns the current page number as if numbering starts on
* page one, regardless of the indexing of the underlying
* server API.
*
* @returns {integer} The current page number.
*/
getPageNumber: function() {
return this.state.currentPage + (1 - this.state.firstPage);
},
/**
* Returns the total pages of the collection based on
* total records and page size
*
* @returns {integer} Total number of pages.
*/
getTotalPages: function() {
return this.state.totalPages;
},
/**
* Returns the total number of records the collection has
*
* @returns {integer} Total number of records.
*/
getTotalRecords: function() {
return this.state.totalRecords;
},
/**
* Returns the number of records per page
*
* @returns {integer} Number of records per page.
*/
getPageSize: function() {
return this.state.pageSize;
},
/**
* Sets the current page of the collection. Page is assumed
* to be one indexed, regardless of the indexing of the
* underlying server API. If there is an error fetching the
* page, the Backbone 'error' event is triggered and the
* page does not change. A 'page_changed' event is triggered
* on a successful page change.
*
* @param page {integer} one-indexed page to change to.
*/
setPage: function(page) {
var oldPage = this.state.currentPage,
self = this,
deferred = $.Deferred();
this.getPage(page - (1 - this.state.firstPage), {reset: true}).then(
function() {
self.isStale = false;
self.trigger('page_changed');
deferred.resolve();
},
function() {
self.state.currentPage = oldPage;
deferred.fail();
}
);
return deferred.promise();
},
/**
* Refreshes the collection if it has been marked as stale.
*
* @returns {promise} Returns a promise representing the
* refresh.
*/
refresh: function() {
var deferred = $.Deferred();
if (this.isStale) {
this.setPage(1)
.done(function() {
deferred.resolve();
});
} else {
deferred.resolve();
}
return deferred.promise();
},
/**
* Returns true if the collection has a next page, false
* otherwise.
*
* @returns {boolean} Returns true if the collection has a next page.
*/
hasNextPage: function() {
return this.getPageNumber() < this.state.totalPages;
},
/**
* Returns true if the collection has a previous page, false
* otherwise.
*
* @returns {boolean} Returns true if the collection has a previous page.
*/
hasPreviousPage: function() {
return this.getPageNumber() > 1;
},
/**
* Moves the collection to the next page if it exists.
*/
nextPage: function() {
if (this.hasNextPage()) {
this.setPage(this.getPageNumber() + 1);
}
},
/**
* Moves the collection to the previous page if it exists.
*/
previousPage: function() {
if (this.hasPreviousPage()) {
this.setPage(this.getPageNumber() - 1);
}
},
/**
* Adds the given field to the list of fields that can be
* sorted on.
*
* @param fieldName {string} name of the field for the server API
* @param displayName {string} name of the field to display to the
* user
*/
registerSortableField: function(fieldName, displayName) {
this.addField(this.sortableFields, fieldName, displayName);
},
/**
* Adds the given field to the list of fields that can be
* filtered on.
*
* @param fieldName {string} name of the field for the server API
* @param displayName {string} name of the field to display to the
* user
*/
registerFilterableField: function(fieldName, displayName) {
this.addField(this.filterableFields, fieldName, displayName);
},
/**
* For internal use only. Adds the given field to the given
* collection of fields.
* @param fields {object} object of existing fields
* @param fieldName {string} name of the field for the server API
* @param displayName {string} name of the field to display to the
* user
*/
addField: function(fields, fieldName, displayName) {
var newField = {};
newField[fieldName] = {
displayName: displayName
};
_.extend(fields, newField);
},
/**
* Returns the display name of the field that the collection
* is currently sorted on.
*
* @returns {string} The display name of the sort field.
*/
sortDisplayName: function() {
if (this.state.sortKey) {
return this.sortableFields[this.state.sortKey].displayName;
} else {
return '';
}
},
/**
* Returns the display name of a specified filterable field.
*
* @param fieldName {string} querystring parameter name for the
* filterable field
* @returns {string} The display name of the specified filterable field.
*/
filterDisplayName: function(fieldName) {
if (!_.isUndefined(this.filterableFields[fieldName])) {
return this.filterableFields[fieldName].displayName;
} else {
return '';
}
},
/**
* Sets the field to sort on and marks the collection as
* stale.
*
* @param fieldName {string} name of the field to sort on
* @param toggleDirection {boolean} if true, the sort direction is
* toggled if the given field was already set
*/
setSortField: function(fieldName, toggleDirection) {
var direction = toggleDirection ? 0 - this.state.order : this.state.order;
if (fieldName !== this.state.sortKey || toggleDirection) {
this.setSorting(fieldName, direction);
this.isStale = true;
}
},
/**
* Returns the direction of the current sort.
*
* The return value is one of the following:
*
* - `asc` - indicates that the sort is ascending.
* - `desc` - indicates that the sort is descending.
*
* @returns {string} Returns the direction of the current sort.
*/
sortDirection: function() {
return (this.state.order === -1) ?
PagingCollection.SortDirection.ASCENDING :
PagingCollection.SortDirection.DESCENDING;
},
/**
* Sets the direction of the sort and marks the collection
* as stale. Assumes (and requires) that the sort key has
* already been set.
*
* @param direction {string} either ASCENDING or DESCENDING from
* PagingCollection.SortDirection.
*/
setSortDirection: function(direction) {
var currentOrder = this.state.order,
newOrder = currentOrder;
if (direction === PagingCollection.SortDirection.ASCENDING) {
newOrder = -1;
} else if (direction === PagingCollection.SortDirection.DESCENDING) {
newOrder = 1;
}
if (newOrder !== currentOrder) {
this.setSorting(this.state.sortKey, newOrder);
this.isStale = true;
}
},
/**
* Flips the sort order.
*/
flipSortDirection: function() {
this.setSorting(this.state.sortKey, 0 - this.state.order);
this.isStale = true;
},
/**
* Returns whether this collection has defined a given
* filterable field.
*
* @param fieldName {string} querystring parameter name for the
* filterable field
* @return {boolean} Returns true if this collection has the specified field.
*/
hasRegisteredFilterField: function(fieldName) {
return _.has(this.filterableFields, fieldName) &&
!_.isUndefined(this.filterableFields[fieldName].displayName);
},
/**
* Returns whether this collection has set a filterable field.
*
* @param fieldName {string} querystring parameter name for the
* filterable field
* @return {boolean} Returns true if this collection has set the specified field.
*/
hasSetFilterField: function(fieldName) {
return _.has(this.filterableFields, fieldName) && !_.isNull(this.filterableFields[fieldName].value);
},
/**
* Gets an object of currently active (applied) filters. Excludes
* the active search by default.
* @param {bool} includeSearch - Whether search should be included
* in the result.
* @returns {Object} An object mapping the names of currently active
* filter fields to their values.
*/
getActiveFilterFields: function(includeSearch) {
var activeFilterFields = _.chain(this.filterableFields)
.pick(function(fieldData) {
return !_.isNull(fieldData.value) && !_.isUndefined(fieldData.value);
})
.mapObject(function(data) {
return data.value;
});
if (!includeSearch) {
activeFilterFields = activeFilterFields.omit(PagingCollection.DefaultSearchKey);
}
return activeFilterFields.value();
},
/**
* Gets the value of the given filter field.
*
* @returns {String} the current value of the requested filter
* field. null means that the filter field is not active.
*/
getFilterFieldValue: function(filterFieldName) {
var val = this.getActiveFilterFields(true)[filterFieldName];
return (_.isNull(val) || _.isUndefined(val)) ? null : val;
},
/**
* Sets a filter field to a given value and marks the
* collection as stale.
*
* @param fieldName {string} querystring parameter name for the
* filterable field
* @param value {*} value for the filterable field
*/
setFilterField: function(fieldName, value) {
var queryStringValue;
if (!this.hasRegisteredFilterField(fieldName)) {
this.registerFilterableField(fieldName, '');
}
this.filterableFields[fieldName].value = value;
if (_.isArray(value)) {
queryStringValue = value.join(',');
} else {
queryStringValue = value;
}
this.queryParams[fieldName] = function() {
return queryStringValue || null;
};
this.isStale = true;
},
/**
* Unsets a filterable field and marks the collection as
* stale.
*
* @param fieldName {string} querystring parameter name for the
* filterable field
*/
unsetFilterField: function(fieldName) {
if (this.hasSetFilterField(fieldName)) {
this.setFilterField(fieldName, null);
}
},
/**
* Unsets all of the collections filterable fields and marks
* the collection as stale.
*/
unsetAllFilterFields: function() {
_.each(_.keys(this.filterableFields), _.bind(this.unsetFilterField, this));
},
/**
* Gets the value of the current search string.
*
* @returns {String} the current value of the search string. null
* or undefined means that the filter field is not active.
*/
getSearchString: function() {
return this.getFilterFieldValue(PagingCollection.DefaultSearchKey);
},
/**
* Tells whether a search is currently applied.
*
* @returns {bool} - whether a search is currently applied.
*/
hasActiveSearch: function() {
var currentSearch = this.getSearchString();
return !_.isNull(currentSearch) && currentSearch !== '';
},
/**
* Sets the string to use for a text search and marks the
* collection as stale.
*
* @param searchString {string} A string to search on, or null if no
* search is to be applied.
*/
setSearchString: function(searchString) {
if (searchString !== this.getSearchString()) {
this.setFilterField(PagingCollection.DefaultSearchKey, searchString);
}
},
/**
* Unsets the string to use for a text search and marks the
* collection as stale.
*/
unsetSearchString: function() {
this.unsetFilterField(PagingCollection.DefaultSearchKey);
}
}, {
DefaultSearchKey: 'text_search',
SortDirection: {
ASCENDING: 'asc',
DESCENDING: 'desc'
}
});
return PagingCollection;
});
}).call(
this,
// Use the default 'define' function if available, else use 'RequireJS.define'
typeof define === 'function' && define.amd ? define : RequireJS.define
);