PageRenderTime 53ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/backgrid-0.3.5/test/vendor/js/backbone-pageable.js

https://github.com/kuzbida/backgrid_test
JavaScript | 1352 lines | 648 code | 154 blank | 550 comment | 235 complexity | 08c5e41ff2918a3ea5e6f3b891cc807c MD5 | raw file
Possible License(s): MIT
  1. /*
  2. backbone-pageable 1.4.4
  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. throw new RangeError("`currentPage` must be firstPage <= currentPage " +
  485. (firstPage ? ">" : ">=") +
  486. " totalPages if " + firstPage + "-based. Got " +
  487. currentPage + '.');
  488. }
  489. }
  490. return state;
  491. },
  492. /**
  493. Change the page size of this collection.
  494. Under most if not all circumstances, you should call this method to
  495. change the page size of a pageable collection because it will keep the
  496. pagination state sane. By default, the method will recalculate the
  497. current page number to one that will retain the current page's models
  498. when increasing the page size. When decreasing the page size, this method
  499. will retain the last models to the current page that will fit into the
  500. smaller page size.
  501. If `options.first` is true, changing the page size will also reset the
  502. current page back to the first page instead of trying to be smart.
  503. For server mode operations, changing the page size will trigger a #fetch
  504. and subsequently a `reset` event.
  505. For client mode operations, changing the page size will `reset` the
  506. current page by recalculating the current page boundary on the client
  507. side.
  508. If `options.fetch` is true, a fetch can be forced if the collection is in
  509. client mode.
  510. @param {number} pageSize The new page size to set to #state.
  511. @param {Object} [options] {@link #fetch} options.
  512. @param {boolean} [options.first=false] Reset the current page number to
  513. the first page if `true`.
  514. @param {boolean} [options.fetch] If `true`, force a fetch in client mode.
  515. @throws {TypeError} If `pageSize` is not a finite integer.
  516. @throws {RangeError} If `pageSize` is less than 1.
  517. @chainable
  518. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  519. from fetch or this.
  520. */
  521. setPageSize: function (pageSize, options) {
  522. pageSize = finiteInt(pageSize, "pageSize");
  523. options = options || {first: false};
  524. var state = this.state;
  525. var totalPages = ceil(state.totalRecords / pageSize);
  526. var currentPage = totalPages ?
  527. max(state.firstPage,
  528. floor(totalPages *
  529. (state.firstPage ?
  530. state.currentPage :
  531. state.currentPage + 1) /
  532. state.totalPages)) :
  533. state.firstPage;
  534. state = this.state = this._checkState(_extend({}, state, {
  535. pageSize: pageSize,
  536. currentPage: options.first ? state.firstPage : currentPage,
  537. totalPages: totalPages
  538. }));
  539. return this.getPage(state.currentPage, _omit(options, ["first"]));
  540. },
  541. /**
  542. Switching between client, server and infinite mode.
  543. If switching from client to server mode, the #fullCollection is emptied
  544. first and then deleted and a fetch is immediately issued for the current
  545. page from the server. Pass `false` to `options.fetch` to skip fetching.
  546. If switching to infinite mode, and if `options.models` is given for an
  547. array of models, #links will be populated with a URL per page, using the
  548. default URL for this collection.
  549. If switching from server to client mode, all of the pages are immediately
  550. refetched. If you have too many pages, you can pass `false` to
  551. `options.fetch` to skip fetching.
  552. If switching to any mode from infinite mode, the #links will be deleted.
  553. @param {"server"|"client"|"infinite"} [mode] The mode to switch to.
  554. @param {Object} [options]
  555. @param {boolean} [options.fetch=true] If `false`, no fetching is done.
  556. @param {boolean} [options.resetState=true] If 'false', the state is not
  557. reset, but checked for sanity instead.
  558. @chainable
  559. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  560. from fetch or this if `options.fetch` is `false`.
  561. */
  562. switchMode: function (mode, options) {
  563. if (!_contains(["server", "client", "infinite"], mode)) {
  564. throw new TypeError('`mode` must be one of "server", "client" or "infinite"');
  565. }
  566. options = options || {fetch: true, resetState: true};
  567. var state = this.state = options.resetState ?
  568. _clone(this._initState) :
  569. this._checkState(_extend({}, this.state));
  570. this.mode = mode;
  571. var self = this;
  572. var fullCollection = this.fullCollection;
  573. var handlers = this._handlers = this._handlers || {}, handler;
  574. if (mode != "server" && !fullCollection) {
  575. fullCollection = this._makeFullCollection(options.models || [], options);
  576. fullCollection.pageableCollection = this;
  577. this.fullCollection = fullCollection;
  578. var allHandler = this._makeCollectionEventHandler(this, fullCollection);
  579. _each(["add", "remove", "reset", "sort"], function (event) {
  580. handlers[event] = handler = _.bind(allHandler, {}, event);
  581. self.on(event, handler);
  582. fullCollection.on(event, handler);
  583. });
  584. fullCollection.comparator = this._fullComparator;
  585. }
  586. else if (mode == "server" && fullCollection) {
  587. _each(_keys(handlers), function (event) {
  588. handler = handlers[event];
  589. self.off(event, handler);
  590. fullCollection.off(event, handler);
  591. });
  592. delete this._handlers;
  593. this._fullComparator = fullCollection.comparator;
  594. delete this.fullCollection;
  595. }
  596. if (mode == "infinite") {
  597. var links = this.links = {};
  598. var firstPage = state.firstPage;
  599. var totalPages = ceil(state.totalRecords / state.pageSize);
  600. var lastPage = firstPage === 0 ? max(0, totalPages - 1) : totalPages || firstPage;
  601. for (var i = state.firstPage; i <= lastPage; i++) {
  602. links[i] = this.url;
  603. }
  604. }
  605. else if (this.links) delete this.links;
  606. return options.fetch ?
  607. this.fetch(_omit(options, "fetch", "resetState")) :
  608. this;
  609. },
  610. /**
  611. @return {boolean} `true` if this collection can page backward, `false`
  612. otherwise.
  613. */
  614. hasPrevious: function () {
  615. var state = this.state;
  616. var currentPage = state.currentPage;
  617. if (this.mode != "infinite") return currentPage > state.firstPage;
  618. return !!this.links[currentPage - 1];
  619. },
  620. /**
  621. @return {boolean} `true` if this collection can page forward, `false`
  622. otherwise.
  623. */
  624. hasNext: function () {
  625. var state = this.state;
  626. var currentPage = this.state.currentPage;
  627. if (this.mode != "infinite") return currentPage < state.lastPage;
  628. return !!this.links[currentPage + 1];
  629. },
  630. /**
  631. Fetch the first page in server mode, or reset the current page of this
  632. collection to the first page in client or infinite mode.
  633. @param {Object} options {@link #getPage} options.
  634. @chainable
  635. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  636. from fetch or this.
  637. */
  638. getFirstPage: function (options) {
  639. return this.getPage("first", options);
  640. },
  641. /**
  642. Fetch the previous page in server mode, or reset the current page of this
  643. collection to the previous page in client or infinite mode.
  644. @param {Object} options {@link #getPage} options.
  645. @chainable
  646. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  647. from fetch or this.
  648. */
  649. getPreviousPage: function (options) {
  650. return this.getPage("prev", options);
  651. },
  652. /**
  653. Fetch the next page in server mode, or reset the current page of this
  654. collection to the next page in client mode.
  655. @param {Object} options {@link #getPage} options.
  656. @chainable
  657. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  658. from fetch or this.
  659. */
  660. getNextPage: function (options) {
  661. return this.getPage("next", options);
  662. },
  663. /**
  664. Fetch the last page in server mode, or reset the current page of this
  665. collection to the last page in client mode.
  666. @param {Object} options {@link #getPage} options.
  667. @chainable
  668. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  669. from fetch or this.
  670. */
  671. getLastPage: function (options) {
  672. return this.getPage("last", options);
  673. },
  674. /**
  675. Given a page index, set #state.currentPage to that index. If this
  676. collection is in server mode, fetch the page using the updated state,
  677. otherwise, reset the current page of this collection to the page
  678. specified by `index` in client mode. If `options.fetch` is true, a fetch
  679. can be forced in client mode before resetting the current page. Under
  680. infinite mode, if the index is less than the current page, a reset is
  681. done as in client mode. If the index is greater than the current page
  682. number, a fetch is made with the results **appended** to #fullCollection.
  683. The current page will then be reset after fetching.
  684. @param {number|string} index The page index to go to, or the page name to
  685. look up from #links in infinite mode.
  686. @param {Object} [options] {@link #fetch} options or
  687. [reset](http://backbonejs.org/#Collection-reset) options for client mode
  688. when `options.fetch` is `false`.
  689. @param {boolean} [options.fetch=false] If true, force a {@link #fetch} in
  690. client mode.
  691. @throws {TypeError} If `index` is not a finite integer under server or
  692. client mode, or does not yield a URL from #links under infinite mode.
  693. @throws {RangeError} If `index` is out of bounds.
  694. @chainable
  695. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  696. from fetch or this.
  697. */
  698. getPage: function (index, options) {
  699. var mode = this.mode, fullCollection = this.fullCollection;
  700. options = options || {fetch: false};
  701. var state = this.state,
  702. firstPage = state.firstPage,
  703. currentPage = state.currentPage,
  704. lastPage = state.lastPage,
  705. pageSize = state.pageSize;
  706. var pageNum = index;
  707. switch (index) {
  708. case "first": pageNum = firstPage; break;
  709. case "prev": pageNum = currentPage - 1; break;
  710. case "next": pageNum = currentPage + 1; break;
  711. case "last": pageNum = lastPage; break;
  712. default: pageNum = finiteInt(index, "index");
  713. }
  714. this.state = this._checkState(_extend({}, state, {currentPage: pageNum}));
  715. options.from = currentPage, options.to = pageNum;
  716. var pageStart = (firstPage === 0 ? pageNum : pageNum - 1) * pageSize;
  717. var pageModels = fullCollection && fullCollection.length ?
  718. fullCollection.models.slice(pageStart, pageStart + pageSize) :
  719. [];
  720. if ((mode == "client" || (mode == "infinite" && !_isEmpty(pageModels))) &&
  721. !options.fetch) {
  722. this.reset(pageModels, _omit(options, "fetch"));
  723. return this;
  724. }
  725. if (mode == "infinite") options.url = this.links[pageNum];
  726. return this.fetch(_omit(options, "fetch"));
  727. },
  728. /**
  729. Fetch the page for the provided item offset in server mode, or reset the current page of this
  730. collection to the page for the provided item offset in client mode.
  731. @param {Object} options {@link #getPage} options.
  732. @chainable
  733. @return {XMLHttpRequest|Backbone.PageableCollection} The XMLHttpRequest
  734. from fetch or this.
  735. */
  736. getPageByOffset: function (offset, options) {
  737. if (offset < 0) {
  738. throw new RangeError("`offset must be > 0`");
  739. }
  740. offset = finiteInt(offset);
  741. var page = floor(offset / this.state.pageSize);
  742. if (this.state.firstPage !== 0) page++;
  743. if (page > this.state.lastPage) page = this.state.lastPage;
  744. return this.getPage(page, options);
  745. },
  746. /**
  747. Overidden to make `getPage` compatible with Zepto.
  748. @param {string} method
  749. @param {Backbone.Model|Backbone.Collection} model
  750. @param {Object} [options]
  751. @return {XMLHttpRequest}
  752. */
  753. sync: function (method, model, options) {
  754. var self = this;
  755. if (self.mode == "infinite") {
  756. var success = options.success;
  757. var currentPage = self.state.currentPage;
  758. options.success = function (resp, status, xhr) {
  759. var links = self.links;
  760. var newLinks = self.parseLinks(resp, _extend({xhr: xhr}, options));
  761. if (newLinks.first) links[self.state.firstPage] = newLinks.first;
  762. if (newLinks.prev) links[currentPage - 1] = newLinks.prev;
  763. if (newLinks.next) links[currentPage + 1] = newLinks.next;
  764. if (success) success(resp, status, xhr);
  765. };
  766. }
  767. return (BBColProto.sync || Backbone.sync).call(self, method, model, options);
  768. },
  769. /**
  770. Parse pagination links from the server response. Only valid under
  771. infinite mode.
  772. Given a response body and a XMLHttpRequest object, extract pagination
  773. links from them for infinite paging.
  774. This default implementation parses the RFC 5988 `Link` header and extract
  775. 3 links from it - `first`, `prev`, `next`. If a `previous` link is found,
  776. it will be found in the `prev` key in the returned object hash. Any
  777. subclasses overriding this method __must__ return an object hash having
  778. only the keys above. If `first` is missing, the collection's default URL
  779. is assumed to be the `first` URL. If `prev` or `next` is missing, it is
  780. assumed to be `null`. An empty object hash must be returned if there are
  781. no links found. If either the response or the header contains information
  782. pertaining to the total number of records on the server, #state.totalRecords
  783. must be set to that number. The default implementation uses the `last`
  784. link from the header to calculate it.
  785. @param {*} resp The deserialized response body.
  786. @param {Object} [options]
  787. @param {XMLHttpRequest} [options.xhr] The XMLHttpRequest object for this
  788. response.
  789. @return {Object}
  790. */
  791. parseLinks: function (resp, options) {
  792. var links = {};
  793. var linkHeader = options.xhr.getResponseHeader("Link");
  794. if (linkHeader) {
  795. var relations = ["first", "prev", "previous", "next", "last"];
  796. _each(linkHeader.split(","), function (linkValue) {
  797. var linkParts = linkValue.split(";");
  798. var url = linkParts[0].replace(URL_TRIM_RE, '');
  799. var params = linkParts.slice(1);
  800. _each(params, function (param) {
  801. var paramParts = param.split("=");
  802. var key = paramParts[0].replace(PARAM_TRIM_RE, '');
  803. var value = paramParts[1].replace(PARAM_TRIM_RE, '');
  804. if (key == "rel" && _contains(relations, value)) {
  805. if (value == "previous") links.prev = url;
  806. else links[value] = url;
  807. }
  808. });
  809. });
  810. var last = links.last || '', qsi, qs;
  811. if (qs = (qsi = last.indexOf('?')) ? last.slice(qsi + 1) : '') {
  812. var params = queryStringToParams(qs);
  813. var state = _clone(this.state);
  814. var queryParams = this.queryParams;
  815. var pageSize = state.pageSize;
  816. var totalRecords = params[queryParams.totalRecords] * 1;
  817. var pageNum = params[queryParams.currentPage] * 1;
  818. var totalPages = params[queryParams.totalPages];
  819. if (!totalRecords) {
  820. if (pageNum) totalRecords = (state.firstPage === 0 ?
  821. pageNum + 1 :
  822. pageNum) * pageSize;
  823. else if (totalPages) totalRecords = totalPages * pageSize;
  824. }
  825. if (totalRecords) state.totalRecords = totalRecords;
  826. this.state = this._checkState(state);
  827. }
  828. }
  829. delete links.last;
  830. return links;
  831. },
  832. /**
  833. Parse server response data.
  834. This default implementation assumes the response data is in one of two
  835. structures:
  836. [
  837. {}, // Your new pagination state
  838. [{}, ...] // An array of JSON objects
  839. ]
  840. Or,
  841. [{}] // An array of JSON objects
  842. The first structure is the preferred form because the pagination states
  843. may have been updated on the server side, sending them down again allows
  844. this collection to update its states. If the response has a pagination
  845. state object, it is checked for errors.
  846. The second structure is the
  847. [Backbone.Collection#parse](http://backbonejs.org/#Collection-parse)
  848. default.
  849. **Note:** this method has been further simplified since 1.1.7. While
  850. existing #parse implementations will continue to work, new code is
  851. encouraged to override #parseState and #parseRecords instead.
  852. @param {Object} resp The deserialized response data from the server.
  853. @param {Object} the options for the ajax request
  854. @return {Array.<Object>} An array of model objects
  855. */
  856. parse: function (resp, options) {
  857. var newState = this.parseState(resp, _clone(this.queryParams), _clone(this.state), options);
  858. if (newState) this.state = this._checkState(_extend({}, this.state, newState));
  859. return this.parseRecords(resp, options);
  860. },
  861. /**
  862. Parse server response for server pagination state updates.
  863. This default implementation first checks whether the response has any
  864. state object as documented in #parse. If it exists, a state object is
  865. returned by mapping the server state keys to this pageable collection
  866. instance's query parameter keys using `queryParams`.
  867. It is __NOT__ neccessary to return a full state object complete with all
  868. the mappings defined in #queryParams. Any state object resulted is merged
  869. with a copy of the current pageable collection state and checked for
  870. sanity before actually updating. Most of the time, simply providing a new
  871. `totalRecords` value is enough to trigger a full pagination state
  872. recalculation.
  873. parseState: function (resp, queryParams, state, options) {
  874. return {totalRecords: resp.total_entries};
  875. }
  876. If you want to use header fields use:
  877. parseState: function (resp, queryParams, state, options) {
  878. return {totalRecords: options.xhr.getResponseHeader("X-total")};
  879. }
  880. This method __MUST__ return a new state object instead of directly
  881. modifying the #state object. The behavior of directly modifying #state is
  882. undefined.
  883. @param {Object} resp The deserialized response data from the server.
  884. @param {Object} queryParams A copy of #queryParams.
  885. @param {Object} state A copy of #state.
  886. @param {Object} [options] The options passed through from
  887. `parse`. (backbone >= 0.9.10 only)
  888. @return {Object} A new (partial) state object.
  889. */
  890. parseState: function (resp, queryParams, state, options) {
  891. if (resp && resp.length === 2 && _isObject(resp[0]) && _isArray(resp[1])) {
  892. var newState = _clone(state);
  893. var serverState = resp[0];
  894. _each(_pairs(_omit(queryParams, "directions")), function (kvp) {
  895. var k = kvp[0], v = kvp[1];
  896. var serverVal = serverState[v];
  897. if (!_isUndefined(serverVal) && !_.isNull(serverVal)) newState[k] = serverState[v];
  898. });
  899. if (serverState.order) {
  900. newState.order = _invert(queryParams.directions)[serverState.order] * 1;
  901. }
  902. return newState;
  903. }
  904. },
  905. /**
  906. Parse server response for an array of model objects.
  907. This default implementation first checks whether the response has any
  908. state object as documented in #parse. If it exists, the array of model
  909. objects is assumed to be the second element, otherwise the entire
  910. response is returned directly.
  911. @param {Object} resp The deserialized response data from the server.
  912. @param {Object} [options] The options passed through from the
  913. `parse`. (backbone >= 0.9.10 only)
  914. @return {Array.<Object>} An array of model objects
  915. */
  916. parseRecords: function (resp, options) {
  917. if (resp && resp.length === 2 && _isObject(resp[0]) && _isArray(resp[1])) {
  918. return resp[1];
  919. }
  920. return resp;
  921. },
  922. /**
  923. Fetch a page from the server in server mode, or all the pages in client
  924. mode. Under infinite mode, the current page is refetched by default and
  925. then reset.
  926. The query string is constructed by translating the current pagination
  927. state to your server API query parameter using #queryParams. The current
  928. page will reset after fetch.
  929. @param {Object} [options] Accepts all
  930. [Backbone.Collection#fetch](http://backbonejs.org/#Collection-fetch)
  931. options.
  932. @return {XMLHttpRequest}
  933. */
  934. fetch: function (options) {
  935. options = options || {};
  936. var state = this._checkState(this.state);
  937. var mode = this.mode;
  938. if (mode == "infinite" && !options.url) {
  939. options.url = this.links[state.currentPage];
  940. }
  941. var data = options.data || {};
  942. // dedup query params
  943. var url = _result(options, "url") || _result(this, "url") || '';
  944. var qsi = url.indexOf('?');
  945. if (qsi != -1) {
  946. _extend(data, queryStringToParams(url.slice(qsi + 1)));
  947. url = url.slice(0, qsi);
  948. }
  949. options.url = url;
  950. options.data = data;
  951. // map params except directions
  952. var queryParams = this.mode == "client" ?
  953. _pick(this.queryParams, "sortKey", "order") :
  954. _omit(_pick(this.queryParams, _keys(PageableProto.queryParams)),
  955. "directions");
  956. var i, kvp, k, v, kvps = _pairs(queryParams), thisCopy = _clone(this);
  957. for (i = 0; i < kvps.length; i++) {
  958. kvp = kvps[i], k = kvp[0], v = kvp[1];
  959. v = _isFunction(v) ? v.call(thisCopy) : v;
  960. if (state[k] != null && v != null) {
  961. data[v] = state[k];
  962. }
  963. }
  964. // fix up sorting parameters
  965. if (state.sortKey && state.order) {
  966. data[queryParams.order] = this.queryParams.directions[state.order + ""];
  967. }
  968. else if (!state.sortKey) delete data[queryParams.order];
  969. // map extra query parameters
  970. var extraKvps = _pairs(_omit(this.queryParams,
  971. _keys(PageableProto.queryParams)));
  972. for (i = 0; i < extraKvps.length; i++) {
  973. kvp = extraKvps[i];
  974. v = kvp[1];
  975. v = _isFunction(v) ? v.call(thisCopy) : v;
  976. if (v != null) data[kvp[0]] = v;
  977. }
  978. if (mode != "server") {
  979. var self = this, fullCol = this.fullCollection;
  980. var success = options.success;
  981. options.success = function (col, resp, opts) {
  982. // make sure the caller's intent is obeyed
  983. opts = opts || {};
  984. if (_isUndefined(options.silent)) delete opts.silent;
  985. else opts.silent = options.silent;
  986. var models = col.models;
  987. if (mode == "client") fullCol.reset(models, opts);
  988. else {
  989. fullCol.add(models, _extend({at: fullCol.length},
  990. _extend(opts, {parse: false})));
  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. }));