PageRenderTime 94ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/ajax/libs/backbone-pageable/1.3.2/backbone-pageable.js

https://gitlab.com/Blueprint-Marketing/cdnjs
JavaScript | 1325 lines | 625 code | 152 blank | 548 comment | 230 complexity | f860317610755ed637a5fb30583d4536 MD5 | raw file
  1. /*
  2. backbone-pageable 1.3.2
  3. http://github.com/wyuenho/backbone-pageable
  4. Copyright (c) 2013 Jimmy Yuen Ho Wong
  5. Licensed under the MIT @license.
  6. */
  7. (function (factory) {
  8. // CommonJS
  9. if (typeof exports == "object") {
  10. module.exports = factory(require("underscore"), require("backbone"));
  11. }
  12. // AMD
  13. else if (typeof define == "function" && define.amd) {
  14. define(["underscore", "backbone"], factory);
  15. }
  16. // Browser
  17. else if (typeof _ !== "undefined" && typeof Backbone !== "undefined") {
  18. var oldPageableCollection = Backbone.PageableCollection;
  19. var PageableCollection = factory(_, Backbone);
  20. /**
  21. __BROWSER ONLY__
  22. If you already have an object named `PageableCollection` attached to the
  23. `Backbone` module, you can use this to return a local reference to this
  24. Backbone.PageableCollection class and reset the name
  25. Backbone.PageableCollection to its previous definition.
  26. // The left hand side gives you a reference to this
  27. // Backbone.PageableCollection implementation, the right hand side
  28. // resets Backbone.PageableCollection to your other
  29. // Backbone.PageableCollection.
  30. var PageableCollection = Backbone.PageableCollection.noConflict();
  31. @static
  32. @member Backbone.PageableCollection
  33. @return {Backbone.PageableCollection}
  34. */
  35. Backbone.PageableCollection.noConflict = function () {
  36. Backbone.PageableCollection = oldPageableCollection;
  37. return PageableCollection;
  38. };
  39. }
  40. }(function (_, Backbone) {
  41. "use strict";
  42. var _extend = _.extend;
  43. var _omit = _.omit;
  44. var _clone = _.clone;
  45. var _each = _.each;
  46. var _pick = _.pick;
  47. var _contains = _.contains;
  48. var _isEmpty = _.isEmpty;
  49. var _pairs = _.pairs;
  50. var _invert = _.invert;
  51. var _isArray = _.isArray;
  52. var _isFunction = _.isFunction;
  53. var _isObject = _.isObject;
  54. var _keys = _.keys;
  55. var _isUndefined = _.isUndefined;
  56. var _result = _.result;
  57. var ceil = Math.ceil;
  58. var floor = Math.floor;
  59. var max = Math.max;
  60. var BBColProto = Backbone.Collection.prototype;
  61. function finiteInt (val, name) {
  62. if (!_.isNumber(val) || _.isNaN(val) || !_.isFinite(val) || ~~val !== val) {
  63. throw new TypeError("`" + name + "` must be a finite integer");
  64. }
  65. return val;
  66. }
  67. function queryStringToParams (qs) {
  68. var kvp, k, v, ls, params = {}, decode = decodeURIComponent;
  69. var kvps = qs.split('&');
  70. for (var i = 0, l = kvps.length; i < l; i++) {
  71. var param = kvps[i];
  72. kvp = param.split('='), k = kvp[0], v = kvp[1] || true;
  73. k = decode(k), ls = params[k];
  74. if (_isArray(ls)) ls.push(v);
  75. else if (ls) params[k] = [ls, v];
  76. else params[k] = v;
  77. }
  78. return params;
  79. }
  80. var PARAM_TRIM_RE = /[\s'"]/g;
  81. var URL_TRIM_RE = /[<>\s'"]/g;
  82. /**
  83. Drop-in replacement for Backbone.Collection. Supports server-side and
  84. client-side pagination and sorting. Client-side mode also support fully
  85. multi-directional synchronization of changes between pages.
  86. @class Backbone.PageableCollection
  87. @extends Backbone.Collection
  88. */
  89. var PageableCollection = Backbone.PageableCollection = Backbone.Collection.extend({
  90. /**
  91. The container object to store all pagination states.
  92. You can override the default state by extending this class or specifying
  93. them in an `options` hash to the constructor.
  94. @property {Object} state
  95. @property {0|1} [state.firstPage=1] The first page index. Set to 0 if
  96. your server API uses 0-based indices. You should only override this value
  97. during extension, initialization or reset by the server after
  98. fetching. This value should be read only at other times.
  99. @property {number} [state.lastPage=null] The last page index. This value
  100. is __read only__ and it's calculated based on whether `firstPage` is 0 or
  101. 1, during bootstrapping, fetching and resetting. Please don't change this
  102. value under any circumstances.
  103. @property {number} [state.currentPage=null] The current page index. You
  104. should only override this value during extension, initialization or reset
  105. by the server after fetching. This value should be read only at other
  106. times. Can be a 0-based or 1-based index, depending on whether
  107. `firstPage` is 0 or 1. If left as default, it will be set to `firstPage`
  108. on initialization.
  109. @property {number} [state.pageSize=25] How many records to show per
  110. page. This value is __read only__ after initialization, if you want to
  111. change the page size after initialization, you must call #setPageSize.
  112. @property {number} [state.totalPages=null] How many pages there are. This
  113. value is __read only__ and it is calculated from `totalRecords`.
  114. @property {number} [state.totalRecords=null] How many records there
  115. are. This value is __required__ under server mode. This value is optional
  116. for client mode as the number will be the same as the number of models
  117. during bootstrapping and during fetching, either supplied by the server
  118. in the metadata, or calculated from the size of the response.
  119. @property {string} [state.sortKey=null] The model attribute to use for
  120. sorting.
  121. @property {-1|0|1} [state.order=-1] The order to use for sorting. Specify
  122. -1 for ascending order or 1 for descending order. If 0, no client side
  123. sorting will be done and the order query parameter will not be sent to
  124. the server during a fetch.
  125. */
  126. state: {
  127. firstPage: 1,
  128. lastPage: null,
  129. currentPage: null,
  130. pageSize: 25,
  131. totalPages: null,
  132. totalRecords: null,
  133. sortKey: null,
  134. order: -1
  135. },
  136. /**
  137. @property {"server"|"client"|"infinite"} [mode="server"] The mode of
  138. operations for this collection. `"server"` paginates on the server-side,
  139. `"client"` paginates on the client-side and `"infinite"` paginates on the
  140. server-side for APIs that do not support `totalRecords`.
  141. */
  142. mode: "server",
  143. /**
  144. A translation map to convert Backbone.PageableCollection state attributes
  145. to the query parameters accepted by your server API.
  146. You can override the default state by extending this class or specifying
  147. them in `options.queryParams` object hash to the constructor.
  148. @property {Object} queryParams
  149. @property {string} [queryParams.currentPage="page"]
  150. @property {string} [queryParams.pageSize="per_page"]
  151. @property {string} [queryParams.totalPages="total_pages"]
  152. @property {string} [queryParams.totalRecords="total_entries"]
  153. @property {string} [queryParams.sortKey="sort_by"]
  154. @property {string} [queryParams.order="order"]
  155. @property {string} [queryParams.directions={"-1": "asc", "1": "desc"}] A
  156. map for translating a Backbone.PageableCollection#state.order constant to
  157. the ones your server API accepts.
  158. */
  159. queryParams: {
  160. currentPage: "page",
  161. pageSize: "per_page",
  162. totalPages: "total_pages",
  163. totalRecords: "total_entries",
  164. sortKey: "sort_by",
  165. order: "order",
  166. directions: {
  167. "-1": "asc",
  168. "1": "desc"
  169. }
  170. },
  171. /**
  172. __CLIENT MODE ONLY__
  173. This collection is the internal storage for the bootstrapped or fetched
  174. models. You can use this if you want to operate on all the pages.
  175. @property {Backbone.Collection} fullCollection
  176. */
  177. /**
  178. Given a list of models or model attributues, bootstraps the full
  179. collection in client mode or infinite mode, or just the page you want in
  180. server mode.
  181. If you want to initialize a collection to a different state than the
  182. default, you can specify them in `options.state`. Any state parameters
  183. supplied will be merged with the default. If you want to change the
  184. default mapping from #state keys to your server API's query parameter
  185. names, you can specifiy an object hash in `option.queryParams`. Likewise,
  186. any mapping provided will be merged with the default. Lastly, all
  187. Backbone.Collection constructor options are also accepted.
  188. See:
  189. - Backbone.PageableCollection#state
  190. - Backbone.PageableCollection#queryParams
  191. - [Backbone.Collection#initialize](http://backbonejs.org/#Collection-constructor)
  192. @param {Array.<Object>} [models]
  193. @param {Object} [options]
  194. @param {function(*, *): number} [options.comparator] If specified, this
  195. comparator is set to the current page under server mode, or the #fullCollection
  196. otherwise.
  197. @param {boolean} [options.full] If `false` and either a
  198. `options.comparator` or `sortKey` is defined, the comparator is attached
  199. to the current page. Default is `true` under client or infinite mode and
  200. the comparator will be attached to the #fullCollection.
  201. @param {Object} [options.state] The state attributes overriding the defaults.
  202. @param {string} [options.state.sortKey] The model attribute to use for
  203. sorting. If specified instead of `options.comparator`, a comparator will
  204. be automatically created using this value, and optionally a sorting order
  205. specified in `options.state.order`. The comparator is then attached to
  206. the new collection instance.
  207. @param {-1|1} [options.state.order] The order to use for sorting. Specify
  208. -1 for ascending order and 1 for descending order.
  209. @param {Object} [options.queryParam]
  210. */
  211. constructor: function (models, options) {
  212. Backbone.Collection.apply(this, arguments);
  213. options = options || {};
  214. var mode = this.mode = options.mode || this.mode || PageableProto.mode;
  215. var queryParams = _extend({}, PageableProto.queryParams, this.queryParams,
  216. options.queryParams || {});
  217. queryParams.directions = _extend({},
  218. PageableProto.queryParams.directions,
  219. this.queryParams.directions,
  220. queryParams.directions || {});
  221. this.queryParams = queryParams;
  222. var state = this.state = _extend({}, PageableProto.state, this.state,
  223. options.state || {});
  224. state.currentPage = state.currentPage == null ?
  225. state.firstPage :
  226. state.currentPage;
  227. if (!_isArray(models)) models = models ? [models] : [];
  228. if (mode != "server" && state.totalRecords == null && !_isEmpty(models)) {
  229. state.totalRecords = models.length;
  230. }
  231. this.switchMode(mode, _extend({fetch: false,
  232. resetState: false,
  233. models: models}, options));
  234. var comparator = options.comparator;
  235. if (state.sortKey && !comparator) {
  236. this.setSorting(state.sortKey, state.order, options);
  237. }
  238. if (mode != "server") {
  239. var fullCollection = this.fullCollection;
  240. if (comparator && options.full) {
  241. delete this.comparator;
  242. fullCollection.comparator = comparator;
  243. }
  244. if (options.full) fullCollection.sort();
  245. // make sure the models in the current page and full collection have the
  246. // same references
  247. if (models && !_isEmpty(models)) {
  248. this.getPage(state.currentPage);
  249. models.splice.apply(models, [0, models.length].concat(this.models));
  250. }
  251. }
  252. this._initState = _clone(this.state);
  253. },
  254. /**
  255. Makes a Backbone.Collection that contains all the pages.
  256. @private
  257. @param {Array.<Object|Backbone.Model>} models
  258. @param {Object} options Options for Backbone.Collection constructor.
  259. @return {Backbone.Collection}
  260. */
  261. _makeFullCollection: function (models, options) {
  262. var properties = ["url", "model", "sync", "comparator"];
  263. var thisProto = this.constructor.prototype;
  264. var i, length, prop;
  265. var proto = {};
  266. for (i = 0, length = properties.length; i < length; i++) {
  267. prop = properties[i];
  268. if (!_isUndefined(thisProto[prop])) {
  269. proto[prop] = thisProto[prop];
  270. }
  271. }
  272. var fullCollection = new (Backbone.Collection.extend(proto))(models, options);
  273. for (i = 0, length = properties.length; i < length; i++) {
  274. prop = properties[i];
  275. if (this[prop] !== thisProto[prop]) {
  276. fullCollection[prop] = this[prop];
  277. }
  278. }
  279. return fullCollection;
  280. },
  281. /**
  282. Factory method that returns a Backbone event handler that responses to
  283. the `add`, `remove`, `reset`, and the `sort` events. The returned event
  284. handler will synchronize the current page collection and the full
  285. collection's models.
  286. @private
  287. @param {Backbone.PageableCollection} pageCol
  288. @param {Backbone.Collection} fullCol
  289. @return {function(string, Backbone.Model, Backbone.Collection, Object)}
  290. Collection event handler
  291. */
  292. _makeCollectionEventHandler: function (pageCol, fullCol) {
  293. return function collectionEventHandler (event, model, collection, options) {
  294. var handlers = pageCol._handlers;
  295. _each(_keys(handlers), function (event) {
  296. var handler = handlers[event];
  297. pageCol.off(event, handler);
  298. fullCol.off(event, handler);
  299. });
  300. var state = _clone(pageCol.state);
  301. var firstPage = state.firstPage;
  302. var currentPage = firstPage === 0 ?
  303. state.currentPage :
  304. state.currentPage - 1;
  305. var pageSize = state.pageSize;
  306. var pageStart = currentPage * pageSize, pageEnd = pageStart + pageSize;
  307. if (event == "add") {
  308. var pageIndex, fullIndex, addAt, colToAdd, options = options || {};
  309. if (collection == fullCol) {
  310. fullIndex = fullCol.indexOf(model);
  311. if (fullIndex >= pageStart && fullIndex < pageEnd) {
  312. colToAdd = pageCol;
  313. pageIndex = addAt = fullIndex - pageStart;
  314. }
  315. }
  316. else {
  317. pageIndex = pageCol.indexOf(model);
  318. fullIndex = pageStart + pageIndex;
  319. colToAdd = fullCol;
  320. var addAt = !_isUndefined(options.at) ?
  321. options.at + pageStart :
  322. fullIndex;
  323. }
  324. ++state.totalRecords;
  325. pageCol.state = pageCol._checkState(state);
  326. if (colToAdd) {
  327. colToAdd.add(model, _extend({}, options || {}, {at: addAt}));
  328. var modelToRemove = pageIndex >= pageSize ?
  329. model :
  330. !_isUndefined(options.at) && addAt < pageEnd && pageCol.length > pageSize ?
  331. pageCol.at(pageSize) :
  332. null;
  333. if (modelToRemove) {
  334. var addHandlers = collection._events.add || [],
  335. popOptions = {onAdd: true};
  336. if (addHandlers.length) {
  337. var lastAddHandler = addHandlers[addHandlers.length - 1];
  338. var oldCallback = lastAddHandler.callback;
  339. lastAddHandler.callback = function () {
  340. try {
  341. oldCallback.apply(this, arguments);
  342. pageCol.remove(modelToRemove, popOptions);
  343. }
  344. finally {
  345. lastAddHandler.callback = oldCallback;
  346. }
  347. };
  348. }
  349. else pageCol.remove(modelToRemove, popOptions);
  350. }
  351. }
  352. }
  353. // remove the model from the other collection as well
  354. if (event == "remove") {
  355. if (!options.onAdd) {
  356. // decrement totalRecords and update totalPages and lastPage
  357. if (!--state.totalRecords) {
  358. state.totalRecords = null;
  359. state.totalPages = null;
  360. }
  361. else {
  362. var totalPages = state.totalPages = ceil(state.totalRecords / pageSize);
  363. state.lastPage = firstPage === 0 ? totalPages - 1 : totalPages;
  364. if (state.currentPage > totalPages) state.currentPage = state.lastPage;
  365. }
  366. pageCol.state = pageCol._checkState(state);
  367. var nextModel, removedIndex = options.index;
  368. if (collection == pageCol) {
  369. if (nextModel = fullCol.at(pageEnd)) pageCol.push(nextModel);
  370. fullCol.remove(model);
  371. }
  372. else if (removedIndex >= pageStart && removedIndex < pageEnd) {
  373. pageCol.remove(model);
  374. nextModel = fullCol.at(currentPage * (pageSize + removedIndex));
  375. if (nextModel) pageCol.push(nextModel);
  376. }
  377. }
  378. else delete options.onAdd;
  379. }
  380. if (event == "reset") {
  381. options = collection;
  382. collection = model;
  383. // Reset that's not a result of getPage
  384. if (collection === pageCol && options.from == null &&
  385. options.to == null) {
  386. var head = fullCol.models.slice(0, pageStart);
  387. var tail = fullCol.models.slice(pageStart + pageCol.models.length);
  388. fullCol.reset(head.concat(pageCol.models).concat(tail), options);
  389. }
  390. else if (collection === fullCol) {
  391. if (!(state.totalRecords = fullCol.models.length)) {
  392. state.totalRecords = null;
  393. state.totalPages = null;
  394. }
  395. if (pageCol.mode == "client") {
  396. state.lastPage = state.currentPage = state.firstPage;
  397. }
  398. pageCol.state = pageCol._checkState(state);
  399. pageCol.reset(fullCol.models.slice(pageStart, pageEnd),
  400. _extend({}, options, {parse: false}));
  401. }
  402. }
  403. if (event == "sort") {
  404. options = collection;
  405. collection = model;
  406. if (collection === fullCol) {
  407. pageCol.reset(fullCol.models.slice(pageStart, pageEnd),
  408. _extend({}, options, {parse: false}));
  409. }
  410. }
  411. _each(_keys(handlers), function (event) {
  412. var handler = handlers[event];
  413. _each([pageCol, fullCol], function (col) {
  414. col.on(event, handler);
  415. var callbacks = col._events[event] || [];
  416. callbacks.unshift(callbacks.pop());
  417. });
  418. });
  419. };
  420. },
  421. /**
  422. Sanity check this collection's pagination states. Only perform checks
  423. when all the required pagination state values are defined and not null.
  424. If `totalPages` is undefined or null, it is set to `totalRecords` /
  425. `pageSize`. `lastPage` is set according to whether `firstPage` is 0 or 1
  426. when no error occurs.
  427. @private
  428. @throws {TypeError} If `totalRecords`, `pageSize`, `currentPage` or
  429. `firstPage` is not a finite integer.
  430. @throws {RangeError} If `pageSize`, `currentPage` or `firstPage` is out
  431. of bounds.
  432. @return {Object} Returns the `state` object if no error was found.
  433. */
  434. _checkState: function (state) {
  435. var mode = this.mode;
  436. var links = this.links;
  437. var totalRecords = state.totalRecords;
  438. var pageSize = state.pageSize;
  439. var currentPage = state.currentPage;
  440. var firstPage = state.firstPage;
  441. var totalPages = state.totalPages;
  442. if (totalRecords != null && pageSize != null && currentPage != null &&
  443. firstPage != null && (mode == "infinite" ? links : true)) {
  444. totalRecords = finiteInt(totalRecords, "totalRecords");
  445. pageSize = finiteInt(pageSize, "pageSize");
  446. currentPage = finiteInt(currentPage, "currentPage");
  447. firstPage = finiteInt(firstPage, "firstPage");
  448. if (pageSize < 1) {
  449. throw new RangeError("`pageSize` must be >= 1");
  450. }
  451. totalPages = state.totalPages = ceil(totalRecords / pageSize);
  452. if (firstPage < 0 || firstPage > 1) {
  453. throw new RangeError("`firstPage must be 0 or 1`");
  454. }
  455. state.lastPage = firstPage === 0 ? max(0, totalPages - 1) : totalPages;
  456. if (mode == "infinite") {
  457. if (!links[currentPage + '']) {
  458. throw new RangeError("No link found for page " + currentPage);
  459. }
  460. }
  461. else if (currentPage < firstPage ||
  462. (totalPages > 0 &&
  463. (firstPage ? currentPage > totalPages : currentPage >= totalPages))) {
  464. throw new RangeError("`currentPage` must be firstPage <= currentPage " +
  465. (firstPage ? ">" : ">=") +
  466. " totalPages if " + firstPage + "-based. Got " +
  467. currentPage + '.');
  468. }
  469. }
  470. return state;
  471. },
  472. /**
  473. Change the page size of this collection.
  474. Under most if not all circumstances, you should call this method to
  475. change the page size of a pageable collection because it will keep the
  476. pagination state sane. By default, the method will recalculate the
  477. current page number to one that will retain the current page's models
  478. when increasing the page size. When decreasing the page size, this method
  479. will retain the last models to the current page that will fit into the
  480. smaller page size.
  481. If `options.first` is true, changing the page size will also reset the
  482. current page back to the first page instead of trying to be smart.
  483. For server mode operations, changing the page size will trigger a #fetch
  484. and subsequently a `reset` event.
  485. For client mode operations, changing the page size will `reset` the
  486. current page by recalculating the current page boundary on the client
  487. side.
  488. If `options.fetch` is true, a fetch can be forced if the collection is in
  489. client mode.
  490. @param {number} pageSize The new page size to set to #state.
  491. @param {Object} [options] {@link #fetch} options.
  492. @param {boolean} [options.first=false] Reset the current page number to
  493. the first page if `true`.
  494. @param {boolean} [options.fetch] If `true`, force a fetch in client mode.
  495. @throws {TypeError} If `pageSize` is not a finite integer.
  496. @throws {RangeError} If `pageSize` is less than 1.
  497. @chainable
  498. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  499. from fetch or this.
  500. */
  501. setPageSize: function (pageSize, options) {
  502. pageSize = finiteInt(pageSize, "pageSize");
  503. options = options || {first: false};
  504. var state = this.state;
  505. var totalPages = ceil(state.totalRecords / pageSize);
  506. var currentPage = totalPages ?
  507. max(state.firstPage,
  508. floor(totalPages *
  509. (state.firstPage ?
  510. state.currentPage :
  511. state.currentPage + 1) /
  512. state.totalPages)) :
  513. state.firstPage;
  514. state = this.state = this._checkState(_extend({}, state, {
  515. pageSize: pageSize,
  516. currentPage: options.first ? state.firstPage : currentPage,
  517. totalPages: totalPages
  518. }));
  519. return this.getPage(state.currentPage, _omit(options, ["first"]));
  520. },
  521. /**
  522. Switching between client, server and infinite mode.
  523. If switching from client to server mode, the #fullCollection is emptied
  524. first and then deleted and a fetch is immediately issued for the current
  525. page from the server. Pass `false` to `options.fetch` to skip fetching.
  526. If switching to infinite mode, and if `options.models` is given for an
  527. array of models, #links will be populated with a URL per page, using the
  528. default URL for this collection.
  529. If switching from server to client mode, all of the pages are immediately
  530. refetched. If you have too many pages, you can pass `false` to
  531. `options.fetch` to skip fetching.
  532. If switching to any mode from infinite mode, the #links will be deleted.
  533. @param {"server"|"client"|"infinite"} [mode] The mode to switch to.
  534. @param {Object} [options]
  535. @param {boolean} [options.fetch=true] If `false`, no fetching is done.
  536. @param {boolean} [options.resetState=true] If 'false', the state is not
  537. reset, but checked for sanity instead.
  538. @chainable
  539. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  540. from fetch or this if `options.fetch` is `false`.
  541. */
  542. switchMode: function (mode, options) {
  543. if (!_contains(["server", "client", "infinite"], mode)) {
  544. throw new TypeError('`mode` must be one of "server", "client" or "infinite"');
  545. }
  546. options = options || {fetch: true, resetState: true};
  547. var state = this.state = options.resetState ?
  548. _clone(this._initState) :
  549. this._checkState(_extend({}, this.state));
  550. this.mode = mode;
  551. var self = this;
  552. var fullCollection = this.fullCollection;
  553. var handlers = this._handlers = this._handlers || {}, handler;
  554. if (mode != "server" && !fullCollection) {
  555. fullCollection = this._makeFullCollection(options.models || []);
  556. fullCollection.pageableCollection = this;
  557. this.fullCollection = fullCollection;
  558. var allHandler = this._makeCollectionEventHandler(this, fullCollection);
  559. _each(["add", "remove", "reset", "sort"], function (event) {
  560. handlers[event] = handler = _.bind(allHandler, {}, event);
  561. self.on(event, handler);
  562. fullCollection.on(event, handler);
  563. });
  564. fullCollection.comparator = this._fullComparator;
  565. }
  566. else if (mode == "server" && fullCollection) {
  567. _each(_keys(handlers), function (event) {
  568. handler = handlers[event];
  569. self.off(event, handler);
  570. fullCollection.off(event, handler);
  571. });
  572. delete this._handlers;
  573. this._fullComparator = fullCollection.comparator;
  574. delete this.fullCollection;
  575. }
  576. if (mode == "infinite") {
  577. var links = this.links = {};
  578. var firstPage = state.firstPage;
  579. var totalPages = ceil(state.totalRecords / state.pageSize);
  580. var lastPage = firstPage === 0 ? max(0, totalPages - 1) : totalPages || firstPage;
  581. for (var i = state.firstPage; i <= lastPage; i++) {
  582. links[i] = this.url;
  583. }
  584. }
  585. else if (this.links) delete this.links;
  586. return options.fetch ?
  587. this.fetch(_omit(options, "fetch", "resetState")) :
  588. this;
  589. },
  590. /**
  591. @return {boolean} `true` if this collection can page backward, `false`
  592. otherwise.
  593. */
  594. hasPrevious: function () {
  595. var state = this.state;
  596. var currentPage = state.currentPage;
  597. if (this.mode != "infinite") return currentPage > state.firstPage;
  598. return !!this.links[currentPage - 1];
  599. },
  600. /**
  601. @return {boolean} `true` if this collection can page forward, `false`
  602. otherwise.
  603. */
  604. hasNext: function () {
  605. var state = this.state;
  606. var currentPage = this.state.currentPage;
  607. if (this.mode != "infinite") return currentPage < state.lastPage;
  608. return !!this.links[currentPage + 1];
  609. },
  610. /**
  611. Fetch the first page in server mode, or reset the current page of this
  612. collection to the first page in client or infinite mode.
  613. @param {Object} options {@link #getPage} options.
  614. @chainable
  615. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  616. from fetch or this.
  617. */
  618. getFirstPage: function (options) {
  619. return this.getPage("first", options);
  620. },
  621. /**
  622. Fetch the previous page in server mode, or reset the current page of this
  623. collection to the previous page in client or infinite mode.
  624. @param {Object} options {@link #getPage} options.
  625. @chainable
  626. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  627. from fetch or this.
  628. */
  629. getPreviousPage: function (options) {
  630. return this.getPage("prev", options);
  631. },
  632. /**
  633. Fetch the next page in server mode, or reset the current page of this
  634. collection to the next page in client mode.
  635. @param {Object} options {@link #getPage} options.
  636. @chainable
  637. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  638. from fetch or this.
  639. */
  640. getNextPage: function (options) {
  641. return this.getPage("next", options);
  642. },
  643. /**
  644. Fetch the last page in server mode, or reset the current page of this
  645. collection to the last page in client mode.
  646. @param {Object} options {@link #getPage} options.
  647. @chainable
  648. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  649. from fetch or this.
  650. */
  651. getLastPage: function (options) {
  652. return this.getPage("last", options);
  653. },
  654. /**
  655. Given a page index, set #state.currentPage to that index. If this
  656. collection is in server mode, fetch the page using the updated state,
  657. otherwise, reset the current page of this collection to the page
  658. specified by `index` in client mode. If `options.fetch` is true, a fetch
  659. can be forced in client mode before resetting the current page. Under
  660. infinite mode, if the index is less than the current page, a reset is
  661. done as in client mode. If the index is greater than the current page
  662. number, a fetch is made with the results **appended** to #fullCollection.
  663. The current page will then be reset after fetching.
  664. @param {number|string} index The page index to go to, or the page name to
  665. look up from #links in infinite mode.
  666. @param {Object} [options] {@link #fetch} options or
  667. [reset](http://backbonejs.org/#Collection-reset) options for client mode
  668. when `options.fetch` is `false`.
  669. @param {boolean} [options.fetch=false] If true, force a {@link #fetch} in
  670. client mode.
  671. @throws {TypeError} If `index` is not a finite integer under server or
  672. client mode, or does not yield a URL from #links under infinite mode.
  673. @throws {RangeError} If `index` is out of bounds.
  674. @chainable
  675. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  676. from fetch or this.
  677. */
  678. getPage: function (index, options) {
  679. var mode = this.mode, fullCollection = this.fullCollection;
  680. options = options || {fetch: false};
  681. var state = this.state,
  682. firstPage = state.firstPage,
  683. currentPage = state.currentPage,
  684. lastPage = state.lastPage,
  685. pageSize = state.pageSize;
  686. var pageNum = index;
  687. switch (index) {
  688. case "first": pageNum = firstPage; break;
  689. case "prev": pageNum = currentPage - 1; break;
  690. case "next": pageNum = currentPage + 1; break;
  691. case "last": pageNum = lastPage; break;
  692. default: pageNum = finiteInt(index, "index");
  693. }
  694. this.state = this._checkState(_extend({}, state, {currentPage: pageNum}));
  695. options.from = currentPage, options.to = pageNum;
  696. var pageStart = (firstPage === 0 ? pageNum : pageNum - 1) * pageSize;
  697. var pageModels = fullCollection && fullCollection.length ?
  698. fullCollection.models.slice(pageStart, pageStart + pageSize) :
  699. [];
  700. if ((mode == "client" || (mode == "infinite" && !_isEmpty(pageModels))) &&
  701. !options.fetch) {
  702. return this.reset(pageModels, _omit(options, "fetch"));
  703. }
  704. if (mode == "infinite") options.url = this.links[pageNum];
  705. return this.fetch(_omit(options, "fetch"));
  706. },
  707. /**
  708. Fetch the page for the provided item offset in server mode, or reset the current page of this
  709. collection to the page for the provided item offset in client mode.
  710. @param {Object} options {@link #getPage} options.
  711. @chainable
  712. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  713. from fetch or this.
  714. */
  715. getPageByOffset: function (offset, options) {
  716. if (offset < 0) {
  717. throw new RangeError("`offset must be > 0`");
  718. }
  719. offset = finiteInt(offset);
  720. var page = floor(offset / this.state.pageSize);
  721. if (this.state.firstPage !== 0) page++;
  722. if (page > this.state.lastPage) page = this.state.lastPage;
  723. return this.getPage(page, options);
  724. },
  725. /**
  726. Overidden to make `getPage` compatible with Zepto.
  727. @param {string} method
  728. @param {Backbone.Model|Backbone.Collection} model
  729. @param {Object} [options]
  730. @return {XMLHttpRequest}
  731. */
  732. sync: function (method, model, options) {
  733. var self = this;
  734. if (self.mode == "infinite") {
  735. var success = options.success;
  736. var currentPage = self.state.currentPage;
  737. options.success = function (resp, status, xhr) {
  738. var links = self.links;
  739. var newLinks = self.parseLinks(resp, _extend({xhr: xhr}, options));
  740. if (newLinks.first) links[self.state.firstPage] = newLinks.first;
  741. if (newLinks.prev) links[currentPage - 1] = newLinks.prev;
  742. if (newLinks.next) links[currentPage + 1] = newLinks.next;
  743. if (success) success(resp, status, xhr);
  744. };
  745. }
  746. return (BBColProto.sync || Backbone.sync).call(self, method, model, options);
  747. },
  748. /**
  749. Parse pagination links from the server response. Only valid under
  750. infinite mode.
  751. Given a response body and a XMLHttpRequest object, extract pagination
  752. links from them for infinite paging.
  753. This default implementation parses the RFC 5988 `Link` header and extract
  754. 3 links from it - `first`, `prev`, `next`. If a `previous` link is found,
  755. it will be found in the `prev` key in the returned object hash. Any
  756. subclasses overriding this method __must__ return an object hash having
  757. only the keys above. If `first` is missing, the collection's default URL
  758. is assumed to be the `first` URL. If `prev` or `next` is missing, it is
  759. assumed to be `null`. An empty object hash must be returned if there are
  760. no links found. If either the response or the header contains information
  761. pertaining to the total number of records on the server, #state.totalRecords
  762. must be set to that number. The default implementation uses the `last`
  763. link from the header to calculate it.
  764. @param {*} resp The deserialized response body.
  765. @param {Object} [options]
  766. @param {XMLHttpRequest} [options.xhr] The XMLHttpRequest object for this
  767. response.
  768. @return {Object}
  769. */
  770. parseLinks: function (resp, options) {
  771. var links = {};
  772. var linkHeader = options.xhr.getResponseHeader("Link");
  773. if (linkHeader) {
  774. var relations = ["first", "prev", "previous", "next", "last"];
  775. _each(linkHeader.split(","), function (linkValue) {
  776. var linkParts = linkValue.split(";");
  777. var url = linkParts[0].replace(URL_TRIM_RE, '');
  778. var params = linkParts.slice(1);
  779. _each(params, function (param) {
  780. var paramParts = param.split("=");
  781. var key = paramParts[0].replace(PARAM_TRIM_RE, '');
  782. var value = paramParts[1].replace(PARAM_TRIM_RE, '');
  783. if (key == "rel" && _contains(relations, value)) {
  784. if (value == "previous") links.prev = url;
  785. else links[value] = url;
  786. }
  787. });
  788. });
  789. var last = links.last || '', qsi, qs;
  790. if (qs = (qsi = last.indexOf('?')) ? last.slice(qsi + 1) : '') {
  791. var params = queryStringToParams(qs);
  792. var state = _clone(this.state);
  793. var queryParams = this.queryParams;
  794. var pageSize = state.pageSize;
  795. var totalRecords = params[queryParams.totalRecords] * 1;
  796. var pageNum = params[queryParams.currentPage] * 1;
  797. var totalPages = params[queryParams.totalPages];
  798. if (!totalRecords) {
  799. if (pageNum) totalRecords = (state.firstPage === 0 ?
  800. pageNum + 1 :
  801. pageNum) * pageSize;
  802. else if (totalPages) totalRecords = totalPages * pageSize;
  803. }
  804. if (totalRecords) state.totalRecords = totalRecords;
  805. this.state = this._checkState(state);
  806. }
  807. }
  808. delete links.last;
  809. return links;
  810. },
  811. /**
  812. Parse server response data.
  813. This default implementation assumes the response data is in one of two
  814. structures:
  815. [
  816. {}, // Your new pagination state
  817. [{}, ...] // An array of JSON objects
  818. ]
  819. Or,
  820. [{}] // An array of JSON objects
  821. The first structure is the preferred form because the pagination states
  822. may have been updated on the server side, sending them down again allows
  823. this collection to update its states. If the response has a pagination
  824. state object, it is checked for errors.
  825. The second structure is the
  826. [Backbone.Collection#parse](http://backbonejs.org/#Collection-parse)
  827. default.
  828. **Note:** this method has been further simplified since 1.1.7. While
  829. existing #parse implementations will continue to work, new code is
  830. encouraged to override #parseState and #parseRecords instead.
  831. @param {Object} resp The deserialized response data from the server.
  832. @param {Object} the options for the ajax request
  833. @return {Array.<Object>} An array of model objects
  834. */
  835. parse: function (resp, options) {
  836. var newState = this.parseState(resp, _clone(this.queryParams), _clone(this.state), options);
  837. if (newState) this.state = this._checkState(_extend({}, this.state, newState));
  838. return this.parseRecords(resp, options);
  839. },
  840. /**
  841. Parse server response for server pagination state updates.
  842. This default implementation first checks whether the response has any
  843. state object as documented in #parse. If it exists, a state object is
  844. returned by mapping the server state keys to this pageable collection
  845. instance's query parameter keys using `queryParams`.
  846. It is __NOT__ neccessary to return a full state object complete with all
  847. the mappings defined in #queryParams. Any state object resulted is merged
  848. with a copy of the current pageable collection state and checked for
  849. sanity before actually updating. Most of the time, simply providing a new
  850. `totalRecords` value is enough to trigger a full pagination state
  851. recalculation.
  852. parseState: function (resp, queryParams, state, options) {
  853. return {totalRecords: resp.total_entries};
  854. }
  855. If you want to use header fields use:
  856. parseState: function (resp, queryParams, state, options) {
  857. return {totalRecords: options.xhr.getResponseHeader("X-total")};
  858. }
  859. This method __MUST__ return a new state object instead of directly
  860. modifying the #state object. The behavior of directly modifying #state is
  861. undefined.
  862. @param {Object} resp The deserialized response data from the server.
  863. @param {Object} queryParams A copy of #queryParams.
  864. @param {Object} state A copy of #state.
  865. @param {Object} [options] The options passed through from
  866. `parse`. (backbone >= 0.9.10 only)
  867. @return {Object} A new (partial) state object.
  868. */
  869. parseState: function (resp, queryParams, state, options) {
  870. if (resp && resp.length === 2 && _isObject(resp[0]) && _isArray(resp[1])) {
  871. var newState = _clone(state);
  872. var serverState = resp[0];
  873. _each(_pairs(_omit(queryParams, "directions")), function (kvp) {
  874. var k = kvp[0], v = kvp[1];
  875. var serverVal = serverState[v];
  876. if (!_isUndefined(serverVal) && !_.isNull(serverVal)) newState[k] = serverState[v];
  877. });
  878. if (serverState.order) {
  879. newState.order = _invert(queryParams.directions)[serverState.order] * 1;
  880. }
  881. return newState;
  882. }
  883. },
  884. /**
  885. Parse server response for an array of model objects.
  886. This default implementation first checks whether the response has any
  887. state object as documented in #parse. If it exists, the array of model
  888. objects is assumed to be the second element, otherwise the entire
  889. response is returned directly.
  890. @param {Object} resp The deserialized response data from the server.
  891. @param {Object} [options] The options passed through from the
  892. `parse`. (backbone >= 0.9.10 only)
  893. @return {Array.<Object>} An array of model objects
  894. */
  895. parseRecords: function (resp, options) {
  896. if (resp && resp.length === 2 && _isObject(resp[0]) && _isArray(resp[1])) {
  897. return resp[1];
  898. }
  899. return resp;
  900. },
  901. /**
  902. Fetch a page from the server in server mode, or all the pages in client
  903. mode. Under infinite mode, the current page is refetched by default and
  904. then reset.
  905. The query string is constructed by translating the current pagination
  906. state to your server API query parameter using #queryParams. The current
  907. page will reset after fetch.
  908. @param {Object} [options] Accepts all
  909. [Backbone.Collection#fetch](http://backbonejs.org/#Collection-fetch)
  910. options.
  911. @return {XMLHttpRequest}
  912. */
  913. fetch: function (options) {
  914. options = options || {};
  915. var state = this._checkState(this.state);
  916. var mode = this.mode;
  917. if (mode == "infinite" && !options.url) {
  918. options.url = this.links[state.currentPage];
  919. }
  920. var data = options.data || {};
  921. // dedup query params
  922. var url = _result(options, "url") || _result(this, "url") || '';
  923. var qsi = url.indexOf('?');
  924. if (qsi != -1) {
  925. _extend(data, queryStringToParams(url.slice(qsi + 1)));
  926. url = url.slice(0, qsi);
  927. }
  928. options.url = url;
  929. options.data = data;
  930. // map params except directions
  931. var queryParams = this.mode == "client" ?
  932. _pick(this.queryParams, "sortKey", "order") :
  933. _omit(_pick(this.queryParams, _keys(PageableProto.queryParams)),
  934. "directions");
  935. var i, kvp, k, v, kvps = _pairs(queryParams), thisCopy = _clone(this);
  936. for (i = 0; i < kvps.length; i++) {
  937. kvp = kvps[i], k = kvp[0], v = kvp[1];
  938. v = _isFunction(v) ? v.call(thisCopy) : v;
  939. if (state[k] != null && v != null) {
  940. data[v] = state[k];
  941. }
  942. }
  943. // fix up sorting parameters
  944. if (state.sortKey && state.order) {
  945. data[queryParams.order] = this.queryParams.directions[state.order + ""];
  946. }
  947. else if (!state.sortKey) delete data[queryParams.order];
  948. // map extra query parameters
  949. var extraKvps = _pairs(_omit(this.queryParams,
  950. _keys(PageableProto.queryParams)));
  951. for (i = 0; i < extraKvps.length; i++) {
  952. kvp = extraKvps[i];
  953. v = kvp[1];
  954. v = _isFunction(v) ? v.call(thisCopy) : v;
  955. if (v != null) data[kvp[0]] = v;
  956. }
  957. if (mode != "server") {
  958. var self = this, fullCol = this.fullCollection;
  959. var success = options.success;
  960. options.success = function (col, resp, opts) {
  961. // make sure the caller's intent is obeyed
  962. opts = opts || {};
  963. if (_isUndefined(options.silent)) delete opts.silent;
  964. else opts.silent = options.silent;
  965. var models = col.models;
  966. if (mode == "client") fullCol.reset(models, opts);
  967. else fullCol.add(models, _extend({at: fullCol.length}, opts));
  968. if (success) success(col, resp, opts);
  969. };
  970. // silent the first reset from backbone
  971. return BBColProto.fetch.call(self, _extend({}, options, {silent: true}));
  972. }
  973. return BBColProto.fetch.call(this, options);
  974. },
  975. /**
  976. Convenient method for making a `comparator` sorted by a model attribute
  977. identified by `sortKey` and ordered by `order`.
  978. Like a Backbone.Collection, a Backbone.PageableCollection will maintain
  979. the __current page__ in sorted order on the client side if a `comparator`
  980. is attached to it. If the collection is in client mode, you can attach a
  981. comparator to #fullCollection to have all the pages reflect the global
  982. sorting order by specifying an option `full` to `true`. You __must__ call
  983. `sort` manually or #fullCollection.sort after calling this method to
  984. force a resort.
  985. While you can use this method to sort the current page in server mode,
  986. the sorting order may not reflect the global sorting order due to the
  987. additions or removals of the records on the server since the last
  988. fetch. If you want the most updated page in a global sorting order, it is
  989. recommended that you set #state.sortKey and optionally #state.order, and
  990. then call #fetch.
  991. @protected
  992. @param {string} [sortKey=this.state.sortKey] See `state.sortKey`.
  993. @param {number} [order=this.state.order] See `state.order`.
  994. @param {(function(Backbone.Model, string): Object) | string} [sortValue] See #setSorting.
  995. See [Backbone.Collection.comparator](http://backbonejs.org/#Collection-comparator).
  996. */
  997. _makeComparator: function (sortKey, order, sortValue) {
  998. var state = this.state;
  999. sortKey = sortKey || state.sortKey;
  1000. order = order || state.order;
  1001. if (!sortKey || !order) return;
  1002. if (!sortValue) sortValue = function (model, attr) {
  1003. return model.get(attr);
  1004. };
  1005. return function (left, right) {
  1006. var l = sortValue(left, sortKey), r = sortValue(right, sortKey), t;
  1007. if (order === 1) t = l, l = r, r = t;
  1008. if (l === r) return 0;
  1009. else if (l < r) return -1;
  1010. return 1;
  1011. };
  1012. },
  1013. /**
  1014. Adjusts the sorting for this pageable collection.
  1015. Given a `sortKey` and an `order`, sets `state.sortKey` and
  1016. `state.order`. A comparator can be applied on the client side to sort in
  1017. the order defined if `options.side` is `"client"`. By default the
  1018. comparator is applied to the #fullCollection. Set `options.full` to
  1019. `false` to apply a comparator to the current page under any mode. Setting
  1020. `sortKey` to `null` removes the comparator from both the current page and
  1021. the full collection.
  1022. If a `sortValue` function is given, it will be passed the `(model,
  1023. sortKey)` arguments and is used to extract a value from the model during
  1024. comparison sorts. If `sortValue` is not given, `model.get(sortKey)` is
  1025. used for sorting.
  1026. @chainable
  1027. @param {string} sortKey See `state.sortKey`.
  1028. @param {number} [order=this.state.order] See `state.order`.
  1029. @param {Object} [options]
  1030. @param {"server"|"client"} [options.side] By default, `"client"` if
  1031. `mode` is `"client"`, `"server"` otherwise.
  1032. @param {boolean} [options.full=true]
  1033. @param {(function(Backbone.Model, string): Object) | string} [options.sortValue]
  1034. */
  1035. setSorting: function (sortKey, order, options) {
  1036. var state = this.state;
  1037. state.sortKey = sortKey;
  1038. state.order = order = order || state.order;
  1039. var fullCollection = this.fullCollection;
  1040. var delComp = false, delFullComp = false;
  1041. if (!sortKey) delComp = delFullComp = true;
  1042. var mode = this.mode;
  1043. options = _extend({side: mode == "client" ? mode : "server", full: true},
  1044. options);
  1045. var comparator = this._makeComparator(sortKey, order, options.sortValue);
  1046. var full = options.full, side = options.side;
  1047. if (side == "client") {
  1048. if (full) {
  1049. if (fullCollection) fullCollection.comparator = comparator;
  1050. delComp = true;
  1051. }
  1052. else {
  1053. this.comparator = comparator;
  1054. delFullComp = true;
  1055. }
  1056. }
  1057. else if (side == "server" && !full) {
  1058. this.comparator = comparator;
  1059. }
  1060. if (delComp) delete this.comparator;
  1061. if (delFullComp && fullCollection) delete fullCollection.comparator;
  1062. return this;
  1063. }
  1064. });
  1065. var PageableProto = PageableCollection.prototype;
  1066. return PageableCollection;
  1067. }));