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

/assets/js/backbone-pageable.js

https://github.com/rhinoman/backgrid
JavaScript | 1347 lines | 638 code | 155 blank | 554 comment | 233 complexity | ef2637438b835181ccf9d4b6069cff72 MD5 | raw file
Possible License(s): MIT
  1. /*
  2. backbone-pageable 1.3.1
  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 = Backbone.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.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 = max(state.firstPage,
  507. floor(totalPages *
  508. (state.firstPage ?
  509. state.currentPage :
  510. state.currentPage + 1) /
  511. state.totalPages));
  512. state = this.state = this._checkState(_extend({}, state, {
  513. pageSize: pageSize,
  514. currentPage: options.first ? state.firstPage : currentPage,
  515. totalPages: totalPages
  516. }));
  517. return this.getPage(state.currentPage, _omit(options, ["first"]));
  518. },
  519. /**
  520. Switching between client, server and infinite mode.
  521. If switching from client to server mode, the #fullCollection is emptied
  522. first and then deleted and a fetch is immediately issued for the current
  523. page from the server. Pass `false` to `options.fetch` to skip fetching.
  524. If switching to infinite mode, and if `options.models` is given for an
  525. array of models, #links will be populated with a URL per page, using the
  526. default URL for this collection.
  527. If switching from server to client mode, all of the pages are immediately
  528. refetched. If you have too many pages, you can pass `false` to
  529. `options.fetch` to skip fetching.
  530. If switching to any mode from infinite mode, the #links will be deleted.
  531. @param {"server"|"client"|"infinite"} [mode] The mode to switch to.
  532. @param {Object} [options]
  533. @param {boolean} [options.fetch=true] If `false`, no fetching is done.
  534. @param {boolean} [options.resetState=true] If 'false', the state is not
  535. reset, but checked for sanity instead.
  536. @chainable
  537. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  538. from fetch or this if `options.fetch` is `false`.
  539. */
  540. switchMode: function (mode, options) {
  541. if (!_contains(["server", "client", "infinite"], mode)) {
  542. throw new TypeError('`mode` must be one of "server", "client" or "infinite"');
  543. }
  544. options = options || {fetch: true, resetState: true};
  545. var state = this.state = options.resetState ?
  546. _clone(this._initState) :
  547. this._checkState(_extend({}, this.state));
  548. this.mode = mode;
  549. var self = this;
  550. var fullCollection = this.fullCollection;
  551. var handlers = this._handlers = this._handlers || {}, handler;
  552. if (mode != "server" && !fullCollection) {
  553. fullCollection = this._makeFullCollection(options.models || []);
  554. fullCollection.pageableCollection = this;
  555. this.fullCollection = fullCollection;
  556. var allHandler = this._makeCollectionEventHandler(this, fullCollection);
  557. _each(["add", "remove", "reset", "sort"], function (event) {
  558. handlers[event] = handler = _.bind(allHandler, {}, event);
  559. self.on(event, handler);
  560. fullCollection.on(event, handler);
  561. });
  562. fullCollection.comparator = this._fullComparator;
  563. }
  564. else if (mode == "server" && fullCollection) {
  565. _each(_keys(handlers), function (event) {
  566. handler = handlers[event];
  567. self.off(event, handler);
  568. fullCollection.off(event, handler);
  569. });
  570. delete this._handlers;
  571. this._fullComparator = fullCollection.comparator;
  572. delete this.fullCollection;
  573. }
  574. if (mode == "infinite") {
  575. var links = this.links = {};
  576. var firstPage = state.firstPage;
  577. var totalPages = ceil(state.totalRecords / state.pageSize);
  578. var lastPage = firstPage === 0 ? max(0, totalPages - 1) : totalPages || firstPage;
  579. for (var i = state.firstPage; i <= lastPage; i++) {
  580. links[i] = this.url;
  581. }
  582. }
  583. else if (this.links) delete this.links;
  584. return options.fetch ?
  585. this.fetch(_omit(options, "fetch", "resetState")) :
  586. this;
  587. },
  588. /**
  589. @return {boolean} `true` if this collection can page backward, `false`
  590. otherwise.
  591. */
  592. hasPrevious: function () {
  593. var state = this.state;
  594. var currentPage = state.currentPage;
  595. if (this.mode != "infinite") return currentPage > state.firstPage;
  596. return !!this.links[currentPage - 1];
  597. },
  598. /**
  599. @return {boolean} `true` if this collection can page forward, `false`
  600. otherwise.
  601. */
  602. hasNext: function () {
  603. var state = this.state;
  604. var currentPage = this.state.currentPage;
  605. if (this.mode != "infinite") return currentPage < state.lastPage;
  606. return !!this.links[currentPage + 1];
  607. },
  608. /**
  609. Fetch the first page in server mode, or reset the current page of this
  610. collection to the first page in client or infinite mode.
  611. @param {Object} options {@link #getPage} options.
  612. @chainable
  613. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  614. from fetch or this.
  615. */
  616. getFirstPage: function (options) {
  617. return this.getPage("first", options);
  618. },
  619. /**
  620. Fetch the previous page in server mode, or reset the current page of this
  621. collection to the previous page in client or infinite mode.
  622. @param {Object} options {@link #getPage} options.
  623. @chainable
  624. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  625. from fetch or this.
  626. */
  627. getPreviousPage: function (options) {
  628. return this.getPage("prev", options);
  629. },
  630. /**
  631. Fetch the next page in server mode, or reset the current page of this
  632. collection to the next page in client mode.
  633. @param {Object} options {@link #getPage} options.
  634. @chainable
  635. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  636. from fetch or this.
  637. */
  638. getNextPage: function (options) {
  639. return this.getPage("next", options);
  640. },
  641. /**
  642. Fetch the last page in server mode, or reset the current page of this
  643. collection to the last page in client mode.
  644. @param {Object} options {@link #getPage} options.
  645. @chainable
  646. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  647. from fetch or this.
  648. */
  649. getLastPage: function (options) {
  650. return this.getPage("last", options);
  651. },
  652. /**
  653. Given a page index, set #state.currentPage to that index. If this
  654. collection is in server mode, fetch the page using the updated state,
  655. otherwise, reset the current page of this collection to the page
  656. specified by `index` in client mode. If `options.fetch` is true, a fetch
  657. can be forced in client mode before resetting the current page. Under
  658. infinite mode, if the index is less than the current page, a reset is
  659. done as in client mode. If the index is greater than the current page
  660. number, a fetch is made with the results **appended** to
  661. #fullCollection. The current page will then be reset after fetching.
  662. @param {number|string} index The page index to go to, or the page name to
  663. look up from #links in infinite mode.
  664. @param {Object} [options] {@link #fetch} options or
  665. [reset](http://backbonejs.org/#Collection-reset) options for client mode
  666. when `options.fetch` is `false`.
  667. @param {boolean} [options.fetch=false] If true, force a {@link #fetch} in
  668. client mode.
  669. @throws {TypeError} If `index` is not a finite integer under server or
  670. client mode, or does not yield a URL from #links under infinite mode.
  671. @throws {RangeError} If `index` is out of bounds.
  672. @chainable
  673. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  674. from fetch or this.
  675. */
  676. getPage: function (index, options) {
  677. var mode = this.mode, fullCollection = this.fullCollection;
  678. options = options || {fetch: false};
  679. var state = this.state,
  680. firstPage = state.firstPage,
  681. currentPage = state.currentPage,
  682. lastPage = state.lastPage,
  683. pageSize = state.pageSize;
  684. var pageNum = index;
  685. switch (index) {
  686. case "first": pageNum = firstPage; break;
  687. case "prev": pageNum = currentPage - 1; break;
  688. case "next": pageNum = currentPage + 1; break;
  689. case "last": pageNum = lastPage; break;
  690. default: pageNum = finiteInt(index, "index");
  691. }
  692. this.state = this._checkState(_extend({}, state, {currentPage: pageNum}));
  693. options.from = currentPage, options.to = pageNum;
  694. var pageStart = (firstPage === 0 ? pageNum : pageNum - 1) * pageSize;
  695. var pageModels = fullCollection && fullCollection.length ?
  696. fullCollection.models.slice(pageStart, pageStart + pageSize) :
  697. [];
  698. if ((mode == "client" || (mode == "infinite" && !_isEmpty(pageModels))) &&
  699. !options.fetch) {
  700. return this.reset(pageModels, _omit(options, "fetch"));
  701. }
  702. if (mode == "infinite") options.url = this.links[pageNum];
  703. return this.fetch(_omit(options, "fetch"));
  704. },
  705. /**
  706. Fetch the page for the provided item offset in server mode, or reset the current page of this
  707. collection to the page for the provided item offset in client mode.
  708. @param {Object} options {@link #getPage} options.
  709. @chainable
  710. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  711. from fetch or this.
  712. */
  713. getPageByOffset: function (offset, options) {
  714. if (offset < 0) {
  715. throw new RangeError("`offset must be > 0`");
  716. }
  717. offset = finiteInt(offset);
  718. var page = floor(offset / this.state.pageSize);
  719. if (this.state.firstPage !== 0) page++;
  720. if (page > this.state.lastPage) page = this.state.lastPage;
  721. return this.getPage(page, options);
  722. },
  723. /**
  724. Overidden to make `getPage` compatible with Zepto.
  725. @param {string} method
  726. @param {Backbone.Model|Backbone.Collection} model
  727. @param {Object} [options]
  728. @return {XMLHttpRequest}
  729. */
  730. sync: function (method, model, options) {
  731. var self = this;
  732. if (self.mode == "infinite") {
  733. var success = options.success;
  734. var currentPage = self.state.currentPage;
  735. options.success = function (resp, status, xhr) {
  736. var links = self.links;
  737. var newLinks = self.parseLinks(resp, _extend({xhr: xhr}, options));
  738. if (newLinks.first) links[self.state.firstPage] = newLinks.first;
  739. if (newLinks.prev) links[currentPage - 1] = newLinks.prev;
  740. if (newLinks.next) links[currentPage + 1] = newLinks.next;
  741. if (success) success(resp, status, xhr);
  742. };
  743. }
  744. return (BBColProto.sync || Backbone.sync).call(self, method, model, options);
  745. },
  746. /**
  747. Parse pagination links from the server response. Only valid under
  748. infinite mode.
  749. Given a response body and a XMLHttpRequest object, extract pagination
  750. links from them for infinite paging.
  751. This default implementation parses the RFC 5988 `Link` header and extract
  752. 3 links from it - `first`, `prev`, `next`. If a `previous` link is found,
  753. it will be found in the `prev` key in the returned object hash. Any
  754. subclasses overriding this method __must__ return an object hash having
  755. only the keys above. If `first` is missing, the collection's default URL
  756. is assumed to be the `first` URL. If `prev` or `next` is missing, it is
  757. assumed to be `null`. An empty object hash must be returned if there are
  758. no links found. If either the response or the header contains information
  759. pertaining to the total number of records on the server,
  760. #state.totalRecords must be set to that number. The default
  761. implementation uses the `last` link from the header to calculate it.
  762. @param {*} resp The deserialized response body.
  763. @param {Object} [options]
  764. @param {XMLHttpRequest} [options.xhr] The XMLHttpRequest object for this
  765. response.
  766. @return {Object}
  767. */
  768. parseLinks: function (resp, options) {
  769. var links = {};
  770. var linkHeader = options.xhr.getResponseHeader("Link");
  771. if (linkHeader) {
  772. var relations = ["first", "prev", "previous", "next", "last"];
  773. _each(linkHeader.split(","), function (linkValue) {
  774. var linkParts = linkValue.split(";");
  775. var url = linkParts[0].replace(URL_TRIM_RE, '');
  776. var params = linkParts.slice(1);
  777. _each(params, function (param) {
  778. var paramParts = param.split("=");
  779. var key = paramParts[0].replace(PARAM_TRIM_RE, '');
  780. var value = paramParts[1].replace(PARAM_TRIM_RE, '');
  781. if (key == "rel" && _contains(relations, value)) {
  782. if (value == "previous") links.prev = url;
  783. else links[value] = url;
  784. }
  785. });
  786. });
  787. var last = links.last || '', qsi, qs;
  788. if (qs = (qsi = last.indexOf('?')) ? last.slice(qsi + 1) : '') {
  789. var params = queryStringToParams(qs);
  790. var state = _clone(this.state);
  791. var queryParams = this.queryParams;
  792. var pageSize = state.pageSize;
  793. var totalRecords = params[queryParams.totalRecords] * 1;
  794. var pageNum = params[queryParams.currentPage] * 1;
  795. var totalPages = params[queryParams.totalPages];
  796. if (!totalRecords) {
  797. if (pageNum) totalRecords = (state.firstPage === 0 ?
  798. pageNum + 1 :
  799. pageNum) * pageSize;
  800. else if (totalPages) totalRecords = totalPages * pageSize;
  801. }
  802. if (totalRecords) state.totalRecords = totalRecords;
  803. this.state = this._checkState(state);
  804. }
  805. }
  806. delete links.last;
  807. return links;
  808. },
  809. /**
  810. Parse server response data.
  811. This default implementation assumes the response data is in one of two
  812. structures:
  813. [
  814. {}, // Your new pagination state
  815. [{}, ...] // An array of JSON objects
  816. ]
  817. Or,
  818. [{}] // An array of JSON objects
  819. The first structure is the preferred form because the pagination states
  820. may have been updated on the server side, sending them down again allows
  821. this collection to update its states. If the response has a pagination
  822. state object, it is checked for errors.
  823. The second structure is the
  824. [Backbone.Collection#parse](http://backbonejs.org/#Collection-parse)
  825. default.
  826. **Note:** this method has been further simplified since 1.1.7. While
  827. existing #parse implementations will continue to work, new code is
  828. encouraged to override #parseState and #parseRecords instead.
  829. @param {Object} resp The deserialized response data from the server.
  830. @param {Object} the options for the ajax request
  831. @return {Array.<Object>} An array of model objects
  832. */
  833. parse: function (resp, options) {
  834. var newState = this.parseState(resp, _clone(this.queryParams), _clone(this.state), options);
  835. if (newState) this.state = this._checkState(_extend({}, this.state, newState));
  836. return this.parseRecords(resp, options);
  837. },
  838. /**
  839. Parse server response for server pagination state updates.
  840. This default implementation first checks whether the response has any
  841. state object as documented in #parse. If it exists, a state object is
  842. returned by mapping the server state keys to this pageable collection
  843. instance's query parameter keys using `queryParams`.
  844. It is __NOT__ neccessary to return a full state object complete with all
  845. the mappings defined in #queryParams. Any state object resulted is merged
  846. with a copy of the current pageable collection state and checked for
  847. sanity before actually updating. Most of the time, simply providing a new
  848. `totalRecords` value is enough to trigger a full pagination state
  849. recalculation.
  850. parseState: function (resp, queryParams, state, options) {
  851. return {totalRecords: resp.total_entries};
  852. }
  853. If you want to use header fields use:
  854. parseState: function (resp, queryParams, state, options) {
  855. return {totalRecords: options.xhr.getResponseHeader("X-total")};
  856. }
  857. This method __MUST__ return a new state object instead of directly
  858. modifying the #state object. The behavior of directly modifying #state is
  859. undefined.
  860. @param {Object} resp The deserialized response data from the server.
  861. @param {Object} queryParams A copy of #queryParams.
  862. @param {Object} state A copy of #state.
  863. @param {Object} [options] The options passed through from
  864. `parse`. (backbone >= 0.9.10 only)
  865. @return {Object} A new (partial) state object.
  866. */
  867. parseState: function (resp, queryParams, state, options) {
  868. if (resp && resp.length === 2 && _isObject(resp[0]) && _isArray(resp[1])) {
  869. var newState = _clone(state);
  870. var serverState = resp[0];
  871. _each(_pairs(_omit(queryParams, "directions")), function (kvp) {
  872. var k = kvp[0], v = kvp[1];
  873. var serverVal = serverState[v];
  874. if (!_isUndefined(serverVal) && !_.isNull(serverVal)) newState[k] = serverState[v];
  875. });
  876. if (serverState.order) {
  877. newState.order = _invert(queryParams.directions)[serverState.order] * 1;
  878. }
  879. return newState;
  880. }
  881. },
  882. /**
  883. Parse server response for an array of model objects.
  884. This default implementation first checks whether the response has any
  885. state object as documented in #parse. If it exists, the array of model
  886. objects is assumed to be the second element, otherwise the entire
  887. response is returned directly.
  888. @param {Object} resp The deserialized response data from the server.
  889. @param {Object} [options] The options passed through from the
  890. `parse`. (backbone >= 0.9.10 only)
  891. @return {Array.<Object>} An array of model objects
  892. */
  893. parseRecords: function (resp, options) {
  894. if (resp && resp.length === 2 && _isObject(resp[0]) && _isArray(resp[1])) {
  895. return resp[1];
  896. }
  897. return resp;
  898. },
  899. /**
  900. Fetch a page from the server in server mode, or all the pages in client
  901. mode. Under infinite mode, the current page is refetched by default and
  902. then reset.
  903. The query string is constructed by translating the current pagination
  904. state to your server API query parameter using #queryParams. The current
  905. page will reset after fetch.
  906. @param {Object} [options] Accepts all
  907. [Backbone.Collection#fetch](http://backbonejs.org/#Collection-fetch)
  908. options.
  909. @return {XMLHttpRequest}
  910. */
  911. fetch: function (options) {
  912. options = options || {};
  913. var state = this._checkState(this.state);
  914. var mode = this.mode;
  915. if (mode == "infinite" && !options.url) {
  916. options.url = this.links[state.currentPage];
  917. }
  918. var data = options.data || {};
  919. // dedup query params
  920. var url = _result(options, "url") || _result(this, "url") || '';
  921. var qsi = url.indexOf('?');
  922. if (qsi != -1) {
  923. _extend(data, queryStringToParams(url.slice(qsi + 1)));
  924. url = url.slice(0, qsi);
  925. }
  926. options.url = url;
  927. options.data = data;
  928. // map params except directions
  929. var queryParams = this.mode == "client" ?
  930. _pick(this.queryParams, "sortKey", "order") :
  931. _omit(_pick(this.queryParams, _keys(PageableProto.queryParams)),
  932. "directions");
  933. var i, kvp, k, v, kvps = _pairs(queryParams), thisCopy = _clone(this);
  934. for (i = 0; i < kvps.length; i++) {
  935. kvp = kvps[i], k = kvp[0], v = kvp[1];
  936. v = _isFunction(v) ? v.call(thisCopy) : v;
  937. if (state[k] != null && v != null) {
  938. data[v] = state[k];
  939. }
  940. }
  941. // fix up sorting parameters
  942. if (state.sortKey && state.order) {
  943. data[queryParams.order] = this.queryParams.directions[state.order + ""];
  944. }
  945. else if (!state.sortKey) delete data[queryParams.order];
  946. // map extra query parameters
  947. var extraKvps = _pairs(_omit(this.queryParams,
  948. _keys(PageableProto.queryParams)));
  949. for (i = 0; i < extraKvps.length; i++) {
  950. kvp = extraKvps[i];
  951. v = kvp[1];
  952. v = _isFunction(v) ? v.call(thisCopy) : v;
  953. if (v != null) data[kvp[0]] = v;
  954. }
  955. var fullCol = this.fullCollection, links = this.links;
  956. if (mode != "server") {
  957. var self = this;
  958. var success = options.success;
  959. options.success = function (col, resp, opts) {
  960. // make sure the caller's intent is obeyed
  961. opts = opts || {};
  962. if (_isUndefined(options.silent)) delete opts.silent;
  963. else opts.silent = options.silent;
  964. var models = col.models;
  965. var currentPage = state.currentPage;
  966. if (mode == "client") fullCol.reset(models, opts);
  967. else if (links[currentPage]) { // refetching a page
  968. var pageSize = state.pageSize;
  969. var pageStart = (state.firstPage === 0 ?
  970. currentPage :
  971. currentPage - 1) * pageSize;
  972. var fullModels = fullCol.models;
  973. var head = fullModels.slice(0, pageStart);
  974. var tail = fullModels.slice(pageStart + pageSize);
  975. fullModels = head.concat(models).concat(tail);
  976. var updateFunc = fullCol.set || fullCol.update;
  977. // Must silent update and trigger reset later because the event
  978. // sychronization handler is temporarily taken out during either add
  979. // or remove, which Collection#set does, so the pageable collection
  980. // will be out of sync if not silenced because adding will trigger
  981. // the sychonization event handler
  982. updateFunc.call(fullCol, fullModels, _extend({silent: true}, opts));
  983. fullCol.trigger("reset", fullCol, opts);
  984. }
  985. // fetching new page
  986. else fullCol.add(models, _extend({at: fullCol.length}, opts));
  987. if (success) success(col, resp, opts);
  988. };
  989. // silent the first reset from backbone
  990. return BBColProto.fetch.call(self, _extend({}, options, {silent: true}));
  991. }
  992. return BBColProto.fetch.call(this, options);
  993. },
  994. /**
  995. Convenient method for making a `comparator` sorted by a model attribute
  996. identified by `sortKey` and ordered by `order`.
  997. Like a Backbone.Collection, a Backbone.PageableCollection will maintain
  998. the __current page__ in sorted order on the client side if a `comparator`
  999. is attached to it. If the collection is in client mode, you can attach a
  1000. comparator to #fullCollection to have all the pages reflect the global
  1001. sorting order by specifying an option `full` to `true`. You __must__ call
  1002. `sort` manually or #fullCollection.sort after calling this method to
  1003. force a resort.
  1004. While you can use this method to sort the current page in server mode,
  1005. the sorting order may not reflect the global sorting order due to the
  1006. additions or removals of the records on the server since the last
  1007. fetch. If you want the most updated page in a global sorting order, it is
  1008. recommended that you set #state.sortKey and optionally #state.order, and
  1009. then call #fetch.
  1010. @protected
  1011. @param {string} [sortKey=this.state.sortKey] See `state.sortKey`.
  1012. @param {number} [order=this.state.order] See `state.order`.
  1013. @param {(function(Backbone.Model, string): Object) | string} [sortValue] See #setSorting.
  1014. See [Backbone.Collection.comparator](http://backbonejs.org/#Collection-comparator).
  1015. */
  1016. _makeComparator: function (sortKey, order, sortValue) {
  1017. var state = this.state;
  1018. sortKey = sortKey || state.sortKey;
  1019. order = order || state.order;
  1020. if (!sortKey || !order) return;
  1021. if (!sortValue) sortValue = function (model, attr) {
  1022. return model.get(attr);
  1023. };
  1024. return function (left, right) {
  1025. var l = sortValue(left, sortKey), r = sortValue(right, sortKey), t;
  1026. if (order === 1) t = l, l = r, r = t;
  1027. if (l === r) return 0;
  1028. else if (l < r) return -1;
  1029. return 1;
  1030. };
  1031. },
  1032. /**
  1033. Adjusts the sorting for this pageable collection.
  1034. Given a `sortKey` and an `order`, sets `state.sortKey` and
  1035. `state.order`. A comparator can be applied on the client side to sort in
  1036. the order defined if `options.side` is `"client"`. By default the
  1037. comparator is applied to the #fullCollection. Set `options.full` to
  1038. `false` to apply a comparator to the current page under any mode. Setting
  1039. `sortKey` to `null` removes the comparator from both the current page and
  1040. the full collection.
  1041. If a `sortValue` function is given, it will be passed the `(model,
  1042. sortKey)` arguments and is used to extract a value from the model during
  1043. comparison sorts. If `sortValue` is not given, `model.get(sortKey)` is
  1044. used for sorting.
  1045. @chainable
  1046. @param {string} sortKey See `state.sortKey`.
  1047. @param {number} [order=this.state.order] See `state.order`.
  1048. @param {Object} [options]
  1049. @param {"server"|"client"} [options.side] By default, `"client"` if
  1050. `mode` is `"client"`, `"server"` otherwise.
  1051. @param {boolean} [options.full=true]
  1052. @param {(function(Backbone.Model, string): Object) | string} [options.sortValue]
  1053. */
  1054. setSorting: function (sortKey, order, options) {
  1055. var state = this.state;
  1056. state.sortKey = sortKey;
  1057. state.order = order = order || state.order;
  1058. var fullCollection = this.fullCollection;
  1059. var delComp = false, delFullComp = false;
  1060. if (!sortKey) delComp = delFullComp = true;
  1061. var mode = this.mode;
  1062. options = _extend({side: mode == "client" ? mode : "server", full: true},
  1063. options);
  1064. var comparator = this._makeComparator(sortKey, order, options.sortValue);
  1065. var full = options.full, side = options.side;
  1066. if (side == "client") {
  1067. if (full) {
  1068. if (fullCollection) fullCollection.comparator = comparator;
  1069. delComp = true;
  1070. }
  1071. else {
  1072. this.comparator = comparator;
  1073. delFullComp = true;
  1074. }
  1075. }
  1076. else if (side == "server" && !full) {
  1077. this.comparator = comparator;
  1078. }
  1079. if (delComp) delete this.comparator;
  1080. if (delFullComp && fullCollection) delete fullCollection.comparator;
  1081. return this;
  1082. }
  1083. });
  1084. var PageableProto = PageableCollection.prototype;
  1085. return PageableCollection;
  1086. }));