PageRenderTime 68ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

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

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