Version 3.18.1
Show:

File: app/js/lazy-model-list.js

  1. /**
  2. Provides the LazyModelList class, which is a ModelList subclass that manages
  3. plain objects instead of fully instantiated model instances.
  4. @module app
  5. @submodule lazy-model-list
  6. @since 3.6.0
  7. **/
  8. /**
  9. LazyModelList is a subclass of ModelList that maintains a list of plain
  10. JavaScript objects rather than a list of Model instances. This makes it
  11. well-suited for managing large amounts of data (on the order of thousands of
  12. items) that would tend to bog down a vanilla ModelList.
  13. The API presented by LazyModelList is the same as that of ModelList, except that
  14. in every case where ModelList would provide a Model instance, LazyModelList
  15. provides a plain JavaScript object. LazyModelList also provides a `revive()`
  16. method that can convert the plain object at a given index into a full Model
  17. instance.
  18. Since the items stored in a LazyModelList are plain objects and not full Model
  19. instances, there are a few caveats to be aware of:
  20. * Since items are plain objects and not Model instances, they contain
  21. properties rather than Model attributes. To retrieve a property, use
  22. `item.foo` rather than `item.get('foo')`. To set a property, use
  23. `item.foo = 'bar'` rather than `item.set('foo', 'bar')`.
  24. * Model attribute getters and setters aren't supported, since items in the
  25. LazyModelList are stored and manipulated as plain objects with simple
  26. properties rather than YUI attributes.
  27. * Changes made to the plain object version of an item will not trigger or
  28. bubble up Model `change` events. However, once an item is revived into a
  29. full Model using the `revive()` method, changes to that Model instance
  30. will trigger and bubble change events as expected.
  31. * Custom `idAttribute` fields are not supported.
  32. * `id` and `clientId` properties _are_ supported. If an item doesn't have a
  33. `clientId` property, one will be generated automatically when the item is
  34. added to a LazyModelList.
  35. LazyModelList is generally much more memory efficient than ModelList when
  36. managing large numbers of items, and adding/removing items is significantly
  37. faster. However, the tradeoff is that LazyModelList is only well-suited for
  38. storing very simple items without complex attributes, and consumers must
  39. explicitly revive items into full Model instances as needed (this is not done
  40. transparently for performance reasons).
  41. @class LazyModelList
  42. @extends ModelList
  43. @constructor
  44. @since 3.6.0
  45. **/
  46. var AttrProto = Y.Attribute.prototype,
  47. GlobalEnv = YUI.namespace('Env.Model'),
  48. Lang = Y.Lang,
  49. YArray = Y.Array,
  50. EVT_ADD = 'add',
  51. EVT_ERROR = 'error',
  52. EVT_RESET = 'reset';
  53. Y.LazyModelList = Y.Base.create('lazyModelList', Y.ModelList, [], {
  54. // -- Lifecycle ------------------------------------------------------------
  55. initializer: function () {
  56. this.after('*:change', this._afterModelChange);
  57. },
  58. // -- Public Methods -------------------------------------------------------
  59. /**
  60. Deletes the specified model from the model cache to release memory. The
  61. model won't be destroyed or removed from the list, just freed from the
  62. cache; it can still be instantiated again using `revive()`.
  63. If no model or model index is specified, all cached models in this list will
  64. be freed.
  65. Note: Specifying an index is faster than specifying a model instance, since
  66. the latter requires an `indexOf()` call.
  67. @method free
  68. @param {Model|Number} [model] Model or index of the model to free. If not
  69. specified, all instantiated models in this list will be freed.
  70. @chainable
  71. @see revive()
  72. **/
  73. free: function (model) {
  74. var index;
  75. if (model) {
  76. index = Lang.isNumber(model) ? model : this.indexOf(model);
  77. if (index >= 0) {
  78. // We don't detach the model because it's not being removed from
  79. // the list, just being freed from memory. If something else
  80. // still holds a reference to it, it may still bubble events to
  81. // the list, but that's okay.
  82. //
  83. // `this._models` is a sparse array, which ensures that the
  84. // indices of models and items match even if we don't have model
  85. // instances for all items.
  86. delete this._models[index];
  87. }
  88. } else {
  89. this._models = [];
  90. }
  91. return this;
  92. },
  93. /**
  94. Overrides ModelList#get() to return a map of property values rather than
  95. performing attribute lookups.
  96. @method get
  97. @param {String} name Property name.
  98. @return {String[]} Array of property values.
  99. @see ModelList.get()
  100. **/
  101. get: function (name) {
  102. if (this.attrAdded(name)) {
  103. return AttrProto.get.apply(this, arguments);
  104. }
  105. return YArray.map(this._items, function (item) {
  106. return item[name];
  107. });
  108. },
  109. /**
  110. Overrides ModelList#getAsHTML() to return a map of HTML-escaped property
  111. values rather than performing attribute lookups.
  112. @method getAsHTML
  113. @param {String} name Property name.
  114. @return {String[]} Array of HTML-escaped property values.
  115. @see ModelList.getAsHTML()
  116. **/
  117. getAsHTML: function (name) {
  118. if (this.attrAdded(name)) {
  119. return Y.Escape.html(AttrProto.get.apply(this, arguments));
  120. }
  121. return YArray.map(this._items, function (item) {
  122. return Y.Escape.html(item[name]);
  123. });
  124. },
  125. /**
  126. Overrides ModelList#getAsURL() to return a map of URL-encoded property
  127. values rather than performing attribute lookups.
  128. @method getAsURL
  129. @param {String} name Property name.
  130. @return {String[]} Array of URL-encoded property values.
  131. @see ModelList.getAsURL()
  132. **/
  133. getAsURL: function (name) {
  134. if (this.attrAdded(name)) {
  135. return encodeURIComponent(AttrProto.get.apply(this, arguments));
  136. }
  137. return YArray.map(this._items, function (item) {
  138. return encodeURIComponent(item[name]);
  139. });
  140. },
  141. /**
  142. Returns the index of the given object or Model instance in this
  143. LazyModelList.
  144. @method indexOf
  145. @param {Model|Object} needle The object or Model instance to search for.
  146. @return {Number} Item index, or `-1` if not found.
  147. @see ModelList.indexOf()
  148. **/
  149. indexOf: function (model) {
  150. return YArray.indexOf(model && model._isYUIModel ?
  151. this._models : this._items, model);
  152. },
  153. /**
  154. Overrides ModelList#reset() to work with plain objects.
  155. @method reset
  156. @param {Object[]|Model[]|ModelList} [models] Models to add.
  157. @param {Object} [options] Options.
  158. @chainable
  159. @see ModelList.reset()
  160. **/
  161. reset: function (items, options) {
  162. items || (items = []);
  163. options || (options = {});
  164. var facade = Y.merge({src: 'reset'}, options);
  165. // Convert `items` into an array of plain objects, since we don't want
  166. // model instances.
  167. items = items._isYUIModelList ? items.map(this._modelToObject) :
  168. YArray.map(items, this._modelToObject);
  169. facade.models = items;
  170. if (options.silent) {
  171. this._defResetFn(facade);
  172. } else {
  173. // Sort the items before firing the reset event.
  174. if (this.comparator) {
  175. items.sort(Y.bind(this._sort, this));
  176. }
  177. this.fire(EVT_RESET, facade);
  178. }
  179. return this;
  180. },
  181. /**
  182. Revives an item (or all items) into a full Model instance. The _item_
  183. argument may be the index of an object in this list, an actual object (which
  184. must exist in the list), or may be omitted to revive all items in the list.
  185. Once revived, Model instances are attached to this list and cached so that
  186. reviving them in the future doesn't require another Model instantiation. Use
  187. the `free()` method to explicitly uncache and detach a previously revived
  188. Model instance.
  189. Note: Specifying an index rather than an object will be faster, since
  190. objects require an `indexOf()` lookup in order to retrieve the index.
  191. @method revive
  192. @param {Number|Object} [item] Index of the object to revive, or the object
  193. itself. If an object, that object must exist in this list. If not
  194. specified, all items in the list will be revived and an array of models
  195. will be returned.
  196. @return {Model|Model[]|null} Revived Model instance, array of revived Model
  197. instances, or `null` if the given index or object was not found in this
  198. list.
  199. @see free()
  200. **/
  201. revive: function (item) {
  202. var i, len, models;
  203. if (item || item === 0) {
  204. return this._revive(Lang.isNumber(item) ? item :
  205. this.indexOf(item));
  206. } else {
  207. models = [];
  208. for (i = 0, len = this._items.length; i < len; i++) {
  209. models.push(this._revive(i));
  210. }
  211. return models;
  212. }
  213. },
  214. /**
  215. Overrides ModelList#toJSON() to use toArray() instead, since it's more
  216. efficient for LazyModelList.
  217. @method toJSON
  218. @return {Object[]} Array of objects.
  219. @see ModelList.toJSON()
  220. **/
  221. toJSON: function () {
  222. return this.toArray();
  223. },
  224. // -- Protected Methods ----------------------------------------------------
  225. /**
  226. Overrides ModelList#add() to work with plain objects.
  227. @method _add
  228. @param {Object|Model} item Object or model to add.
  229. @param {Object} [options] Options.
  230. @return {Object} Added item.
  231. @protected
  232. @see ModelList._add()
  233. **/
  234. _add: function (item, options) {
  235. var facade;
  236. options || (options = {});
  237. // If the item is a model instance, convert it to a plain object.
  238. item = this._modelToObject(item);
  239. // Ensure that the item has a clientId.
  240. if (!('clientId' in item)) {
  241. item.clientId = this._generateClientId();
  242. }
  243. if (this._isInList(item)) {
  244. this.fire(EVT_ERROR, {
  245. error: 'Model is already in the list.',
  246. model: item,
  247. src : 'add'
  248. });
  249. return;
  250. }
  251. facade = Y.merge(options, {
  252. index: 'index' in options ? options.index : this._findIndex(item),
  253. model: item
  254. });
  255. options.silent ? this._defAddFn(facade) : this.fire(EVT_ADD, facade);
  256. return item;
  257. },
  258. /**
  259. Overrides ModelList#clear() to support `this._models`.
  260. @method _clear
  261. @protected
  262. @see ModelList.clear()
  263. **/
  264. _clear: function () {
  265. YArray.each(this._models, this._detachList, this);
  266. this._clientIdMap = {};
  267. this._idMap = {};
  268. this._items = [];
  269. this._models = [];
  270. },
  271. /**
  272. Generates an ad-hoc clientId for a non-instantiated Model.
  273. @method _generateClientId
  274. @return {String} Unique clientId.
  275. @protected
  276. **/
  277. _generateClientId: function () {
  278. GlobalEnv.lastId || (GlobalEnv.lastId = 0);
  279. return this.model.NAME + '_' + (GlobalEnv.lastId += 1);
  280. },
  281. /**
  282. Returns `true` if the given item is in this list, `false` otherwise.
  283. @method _isInList
  284. @param {Object} item Plain object item.
  285. @return {Boolean} `true` if the item is in this list, `false` otherwise.
  286. @protected
  287. **/
  288. _isInList: function (item) {
  289. return !!(('clientId' in item && this._clientIdMap[item.clientId]) ||
  290. ('id' in item && this._idMap[item.id]));
  291. },
  292. /**
  293. Converts a Model instance into a plain object. If _model_ is not a Model
  294. instance, it will be returned as is.
  295. This method differs from Model#toJSON() in that it doesn't delete the
  296. `clientId` property.
  297. @method _modelToObject
  298. @param {Model|Object} model Model instance to convert.
  299. @return {Object} Plain object.
  300. @protected
  301. **/
  302. _modelToObject: function (model) {
  303. if (model._isYUIModel) {
  304. model = model.getAttrs();
  305. delete model.destroyed;
  306. delete model.initialized;
  307. }
  308. return model;
  309. },
  310. /**
  311. Overrides ModelList#_remove() to convert Model instances to indices
  312. before removing to ensure consistency in the `remove` event facade.
  313. @method _remove
  314. @param {Object|Model} item Object or model to remove.
  315. @param {Object} [options] Options.
  316. @return {Object} Removed object.
  317. @protected
  318. **/
  319. _remove: function (item, options) {
  320. // If the given item is a model instance, turn it into an index before
  321. // calling the parent _remove method, since we only want to deal with
  322. // the plain object version.
  323. if (item._isYUIModel) {
  324. item = this.indexOf(item);
  325. }
  326. return Y.ModelList.prototype._remove.call(this, item, options);
  327. },
  328. /**
  329. Revives a single model at the specified index and returns it. This is the
  330. underlying implementation for `revive()`.
  331. @method _revive
  332. @param {Number} index Index of the item to revive.
  333. @return {Model} Revived model.
  334. @protected
  335. **/
  336. _revive: function (index) {
  337. var item, model;
  338. if (index < 0) {
  339. return null;
  340. }
  341. item = this._items[index];
  342. if (!item) {
  343. return null;
  344. }
  345. model = this._models[index];
  346. if (!model) {
  347. model = new this.model(item);
  348. // The clientId attribute is read-only, but revived models should
  349. // have the same clientId as the original object, so we need to set
  350. // it manually.
  351. model._set('clientId', item.clientId);
  352. this._attachList(model);
  353. this._models[index] = model;
  354. }
  355. return model;
  356. },
  357. // -- Event Handlers -------------------------------------------------------
  358. /**
  359. Handles `change` events on revived models and updates the original objects
  360. with the changes.
  361. @method _afterModelChange
  362. @param {EventFacade} e
  363. @protected
  364. **/
  365. _afterModelChange: function (e) {
  366. var changed = e.changed,
  367. item = this._clientIdMap[e.target.get('clientId')],
  368. name;
  369. if (item) {
  370. for (name in changed) {
  371. if (changed.hasOwnProperty(name)) {
  372. item[name] = changed[name].newVal;
  373. }
  374. }
  375. }
  376. },
  377. // -- Default Event Handlers -----------------------------------------------
  378. /**
  379. Overrides ModelList#_defAddFn() to support plain objects.
  380. @method _defAddFn
  381. @param {EventFacade} e
  382. @protected
  383. **/
  384. _defAddFn: function (e) {
  385. var item = e.model;
  386. this._clientIdMap[item.clientId] = item;
  387. if (Lang.isValue(item.id)) {
  388. this._idMap[item.id] = item;
  389. }
  390. this._items.splice(e.index, 0, item);
  391. },
  392. /**
  393. Overrides ModelList#_defRemoveFn() to support plain objects.
  394. @method _defRemoveFn
  395. @param {EventFacade} e
  396. @protected
  397. **/
  398. _defRemoveFn: function (e) {
  399. var index = e.index,
  400. item = e.model,
  401. model = this._models[index];
  402. delete this._clientIdMap[item.clientId];
  403. if ('id' in item) {
  404. delete this._idMap[item.id];
  405. }
  406. if (model) {
  407. this._detachList(model);
  408. }
  409. this._items.splice(index, 1);
  410. this._models.splice(index, 1);
  411. }
  412. });