PageRenderTime 54ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/kolbyjAFK/cdnjs
JavaScript | 1290 lines | 624 code | 153 blank | 513 comment | 228 complexity | ac1189d5b7a3cdfb6f9104dc1943a85e MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception
  1. /*
  2. backbone-pageable 1.2.2
  3. http://github.com/wyuenho/backbone-pageable
  4. Copyright (c) 2013 Jimmy Yuen Ho Wong
  5. Licensed under the MIT @license.
  6. */
  7. (function (factory) {
  8. // CommonJS
  9. if (typeof exports == "object") {
  10. module.exports = factory(require("underscore"), require("backbone"));
  11. }
  12. // AMD
  13. else if (typeof define == "function" && define.amd) {
  14. define(["underscore", "backbone"], factory);
  15. }
  16. // Browser
  17. else if (typeof _ !== "undefined" && typeof Backbone !== "undefined") {
  18. var oldPageableCollection = Backbone.PageableCollection;
  19. var PageableCollection = Backbone.PageableCollection = factory(_, Backbone);
  20. /**
  21. __BROWSER ONLY__
  22. If you already have an object named `PageableCollection` attached to the
  23. `Backbone` module, you can use this to return a local reference to this
  24. Backbone.PageableCollection class and reset the name
  25. Backbone.PageableCollection to its previous definition.
  26. // The left hand side gives you a reference to this
  27. // Backbone.PageableCollection implementation, the right hand side
  28. // resets Backbone.PageableCollection to your other
  29. // Backbone.PageableCollection.
  30. var PageableCollection = Backbone.PageableCollection.noConflict();
  31. @static
  32. @member Backbone.PageableCollection
  33. @return {Backbone.PageableCollection}
  34. */
  35. Backbone.PageableCollection.noConflict = function () {
  36. Backbone.PageableCollection = oldPageableCollection;
  37. return PageableCollection;
  38. };
  39. }
  40. }(function (_, Backbone) {
  41. "use strict";
  42. var _extend = _.extend;
  43. var _omit = _.omit;
  44. var _clone = _.clone;
  45. var _each = _.each;
  46. var _pick = _.pick;
  47. var _contains = _.contains;
  48. var _isEmpty = _.isEmpty;
  49. var _pairs = _.pairs;
  50. var _invert = _.invert;
  51. var _isArray = _.isArray;
  52. var _isFunction = _.isFunction;
  53. var _isObject = _.isObject;
  54. var _keys = _.keys;
  55. var _isUndefined = _.isUndefined;
  56. var _result = _.result;
  57. var ceil = Math.ceil;
  58. var max = Math.max;
  59. var BBColProto = Backbone.Collection.prototype;
  60. function finiteInt (val, name) {
  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. _extend({}, options, {parse: false}));
  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 if (currentPage < firstPage ||
  471. (totalPages > 0 &&
  472. (firstPage ? currentPage > totalPages : currentPage >= totalPages))) {
  473. throw new RangeError("`currentPage` must be firstPage <= currentPage " +
  474. (firstPage ? ">" : ">=") +
  475. " totalPages if " + firstPage + "-based. Got " +
  476. currentPage + '.');
  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 links = {};
  740. var linkHeader = options.xhr.getResponseHeader("Link");
  741. if (linkHeader) {
  742. var relations = ["first", "prev", "previous", "next", "last"];
  743. _each(linkHeader.split(","), function (linkValue) {
  744. var linkParts = linkValue.split(";");
  745. var url = linkParts[0].replace(URL_TRIM_RE, '');
  746. var params = linkParts.slice(1);
  747. _each(params, function (param) {
  748. var paramParts = param.split("=");
  749. var key = paramParts[0].replace(PARAM_TRIM_RE, '');
  750. var value = paramParts[1].replace(PARAM_TRIM_RE, '');
  751. if (key == "rel" && _contains(relations, value)) {
  752. if (value == "previous") links.prev = url;
  753. else links[value] = url;
  754. }
  755. });
  756. });
  757. var last = links.last || '', qsi, qs;
  758. if (qs = (qsi = last.indexOf('?')) ? last.slice(qsi + 1) : '') {
  759. var params = queryStringToParams(qs);
  760. var state = _clone(this.state);
  761. var queryParams = this.queryParams;
  762. var pageSize = state.pageSize;
  763. var totalRecords = params[queryParams.totalRecords] * 1;
  764. var pageNum = params[queryParams.currentPage] * 1;
  765. var totalPages = params[queryParams.totalPages];
  766. if (!totalRecords) {
  767. if (pageNum) totalRecords = (state.firstPage === 0 ?
  768. pageNum + 1 :
  769. pageNum) * pageSize;
  770. else if (totalPages) totalRecords = totalPages * pageSize;
  771. }
  772. if (totalRecords) state.totalRecords = totalRecords;
  773. this.state = this._checkState(state);
  774. }
  775. }
  776. delete links.last;
  777. return links;
  778. },
  779. /**
  780. Parse server response data.
  781. This default implementation assumes the response data is in one of two
  782. structures:
  783. [
  784. {}, // Your new pagination state
  785. [{}, ...] // An array of JSON objects
  786. ]
  787. Or,
  788. [{}] // An array of JSON objects
  789. The first structure is the preferred form because the pagination states
  790. may have been updated on the server side, sending them down again allows
  791. this collection to update its states. If the response has a pagination
  792. state object, it is checked for errors.
  793. The second structure is the
  794. [Backbone.Collection#parse](http://backbonejs.org/#Collection-parse)
  795. default.
  796. **Note:** this method has been further simplified since 1.1.7. While
  797. existing #parse implementations will continue to work, new code is
  798. encouraged to override #parseState and #parseRecords instead.
  799. @param {Object} resp The deserialized response data from the server.
  800. @return {Array.<Object>} An array of model objects
  801. */
  802. parse: function (resp) {
  803. var newState = this.parseState(resp, _clone(this.queryParams), _clone(this.state));
  804. if (newState) this.state = this._checkState(_extend({}, this.state, newState));
  805. return this.parseRecords(resp);
  806. },
  807. /**
  808. Parse server response for server pagination state updates.
  809. This default implementation first checks whether the response has any
  810. state object as documented in #parse. If it exists, a state object is
  811. returned by mapping the server state keys to this pageable collection
  812. instance's query parameter keys using `queryParams`.
  813. It is __NOT__ neccessary to return a full state object complete with all
  814. the mappings defined in #queryParams. Any state object resulted is merged
  815. with a copy of the current pageable collection state and checked for
  816. sanity before actually updating. Most of the time, simply providing a new
  817. `totalRecords` value is enough to trigger a full pagination state
  818. recalculation.
  819. parseState: function (resp, queryParams, state) {
  820. return {totalRecords: resp.total_entries};
  821. }
  822. This method __MUST__ return a new state object instead of directly
  823. modifying the #state object. The behavior of directly modifying #state is
  824. undefined.
  825. @param {Object} resp The deserialized response data from the server.
  826. @param {Object} queryParams A copy of #queryParams.
  827. @param {Object} state A copy of #state.
  828. @return {Object} A new (partial) state object.
  829. */
  830. parseState: function (resp, queryParams, state) {
  831. if (resp && resp.length === 2 && _isObject(resp[0]) && _isArray(resp[1])) {
  832. var newState = _clone(state);
  833. var serverState = resp[0];
  834. _each(_pairs(_omit(queryParams, "directions")), function (kvp) {
  835. var k = kvp[0], v = kvp[1];
  836. var serverVal = serverState[v];
  837. if (!_isUndefined(serverVal) && !_.isNull(serverVal)) 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. var updateFunc = fullCollection.set || fullCollection.update;
  938. updateFunc.call(fullCollection, fullModels,
  939. _extend({silent: true, sort: false}, opts));
  940. if (fullCollection.comparator) fullCollection.sort();
  941. fullCollection.trigger("reset", fullCollection, opts);
  942. }
  943. else { // fetching new page
  944. fullCollection.add(models, _extend({at: fullCollection.length,
  945. silent: true}, opts));
  946. fullCollection.trigger("reset", fullCollection, opts);
  947. }
  948. if (success) success(col, resp, opts);
  949. };
  950. // silent the first reset from backbone
  951. return BBColProto.fetch.call(self, _extend({}, options, {silent: true}));
  952. }
  953. return BBColProto.fetch.call(this, options);
  954. },
  955. /**
  956. Convenient method for making a `comparator` sorted by a model attribute
  957. identified by `sortKey` and ordered by `order`.
  958. Like a Backbone.Collection, a Backbone.PageableCollection will maintain
  959. the __current page__ in sorted order on the client side if a `comparator`
  960. is attached to it. If the collection is in client mode, you can attach a
  961. comparator to #fullCollection to have all the pages reflect the global
  962. sorting order by specifying an option `full` to `true`. You __must__ call
  963. `sort` manually or #fullCollection.sort after calling this method to
  964. force a resort.
  965. While you can use this method to sort the current page in server mode,
  966. the sorting order may not reflect the global sorting order due to the
  967. additions or removals of the records on the server since the last
  968. fetch. If you want the most updated page in a global sorting order, it is
  969. recommended that you set #state.sortKey and optionally #state.order, and
  970. then call #fetch.
  971. @protected
  972. @param {string} [sortKey=this.state.sortKey] See `state.sortKey`.
  973. @param {number} [order=this.state.order] See `state.order`.
  974. See [Backbone.Collection.comparator](http://backbonejs.org/#Collection-comparator).
  975. */
  976. _makeComparator: function (sortKey, order) {
  977. var state = this.state;
  978. sortKey = sortKey || state.sortKey;
  979. order = order || state.order;
  980. if (!sortKey || !order) return;
  981. return function (left, right) {
  982. var l = left.get(sortKey), r = right.get(sortKey), t;
  983. if (order === 1) t = l, l = r, r = t;
  984. if (l === r) return 0;
  985. else if (l < r) return -1;
  986. return 1;
  987. };
  988. },
  989. /**
  990. Adjusts the sorting for this pageable collection.
  991. Given a `sortKey` and an `order`, sets `state.sortKey` and
  992. `state.order`. A comparator can be applied on the client side to sort in
  993. the order defined if `options.side` is `"client"`. By default the
  994. comparator is applied to the #fullCollection. Set `options.full` to
  995. `false` to apply a comparator to the current page under any mode. Setting
  996. `sortKey` to `null` removes the comparator from both the current page and
  997. the full collection.
  998. @chainable
  999. @param {string} sortKey See `state.sortKey`.
  1000. @param {number} [order=this.state.order] See `state.order`.
  1001. @param {Object} [options]
  1002. @param {"server"|"client"} [options.side] By default, `"client"` if
  1003. `mode` is `"client"`, `"server"` otherwise.
  1004. @param {boolean} [options.full=true]
  1005. */
  1006. setSorting: function (sortKey, order, options) {
  1007. var state = this.state;
  1008. state.sortKey = sortKey;
  1009. state.order = order = order || state.order;
  1010. var fullCollection = this.fullCollection;
  1011. var delComp = false, delFullComp = false;
  1012. if (!sortKey) delComp = delFullComp = true;
  1013. var mode = this.mode;
  1014. options = _extend({side: mode == "client" ? mode : "server", full: true},
  1015. options);
  1016. var comparator = this._makeComparator(sortKey, order);
  1017. var full = options.full, side = options.side;
  1018. if (side == "client") {
  1019. if (full) {
  1020. if (fullCollection) fullCollection.comparator = comparator;
  1021. delComp = true;
  1022. }
  1023. else {
  1024. this.comparator = comparator;
  1025. delFullComp = true;
  1026. }
  1027. }
  1028. else if (side == "server" && !full) {
  1029. this.comparator = comparator;
  1030. }
  1031. if (delComp) delete this.comparator;
  1032. if (delFullComp && fullCollection) delete fullCollection.comparator;
  1033. return this;
  1034. }
  1035. });
  1036. var PageableProto = PageableCollection.prototype;
  1037. return PageableCollection;
  1038. }));