PageRenderTime 69ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

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

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