PageRenderTime 243ms CodeModel.GetById 42ms RepoModel.GetById 0ms app.codeStats 1ms

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

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