PageRenderTime 30ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

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

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