PageRenderTime 56ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/backbone-pageable.js

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