PageRenderTime 69ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

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

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