PageRenderTime 59ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

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

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