PageRenderTime 66ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

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

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