Destroyable.js.html 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>JSDoc: Source: Destroyable.js</title>
  6. <script src="scripts/prettify/prettify.js"> </script>
  7. <script src="scripts/prettify/lang-css.js"> </script>
  8. <!--[if lt IE 9]>
  9. <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  10. <![endif]-->
  11. <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
  12. <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
  13. </head>
  14. <body>
  15. <div id="main">
  16. <h1 class="page-title">Source: Destroyable.js</h1>
  17. <section>
  18. <article>
  19. <pre class="prettyprint source linenums"><code>// Licensed Materials - Property of IBM
  20. //
  21. // IBM Watson Analytics
  22. //
  23. // (C) Copyright IBM Corp. 2015, 2018
  24. //
  25. // US Government Users Restricted Rights - Use, duplication or
  26. // disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
  27. module.exports = ( function(
  28. ObjectPolyfill,
  29. decl,
  30. WeakMap,
  31. WeakSet
  32. )
  33. {
  34. "use strict";
  35. /*jshint latedef:false*/
  36. var DestroyableKey = null;
  37. // Try to use an ES6 symbol and be very protective of the destroyed flag.
  38. var DestroyedObjects = new WeakSet();
  39. // grab Array.prototype.map
  40. var map = Array.prototype.map;
  41. /**
  42. * Takes a _target and attempts to resolve it to a Destroyable, even if it is an interface proxy.
  43. * @memberof module:barejs.Destroyable~
  44. * @private
  45. */
  46. function resolveTarget( _target )
  47. {
  48. return decl.isProxy( _target ) &amp;&amp; _target.is( Destroyable ) ? _target.as( DestroyableKey ) : Object( _target );
  49. }
  50. /**
  51. * Check if _target is destroyed.
  52. * @param {module:barejs.Destroyable~Destroyable} _target The destroyable to check
  53. * @returns {boolean} True if the target has been destroyed, false otherwise.
  54. * @memberof module:barejs.Destroyable
  55. */
  56. function isDestroyed( _target )
  57. {
  58. return !!_target &amp;&amp; DestroyedObjects.has( resolveTarget( _target ) );
  59. }
  60. /**
  61. * @class module:barejs.Destroyable~MetaData
  62. * @private
  63. */
  64. function MetaData()
  65. {
  66. this.listeners = [];
  67. this.references = [];
  68. this.referenceHandlers = [];
  69. }
  70. decl.declareClass( MetaData,
  71. /** @lends module:barejs.Destroyable~MetaData */
  72. {
  73. listeners: null,
  74. references: null,
  75. referenceHandlers: null
  76. } );
  77. /**
  78. * Anonymous function closure to keep the WeakMap protected. By using a WeakMap MetaData objects
  79. * have no explicit link back to the Destroyable objects.
  80. * @param {WeakMap} _map WeakMap to store the MetaData objects in.
  81. * @ignore
  82. */
  83. ( function( _map )
  84. {
  85. /**
  86. * Get MetaData for a Destroyable
  87. * @param {module:barejs.Destroyable} _destroyable The Destroyable instance
  88. * @param {boolean} _create Set to true to create the metadata if it doesn't exist.
  89. * @returns {module:barejs.Destroyable~MetaData} The meta data, or null (if create is false and there is none)
  90. */
  91. MetaData.get = function( _destroyable, _create )
  92. {
  93. var meta = _map.get( _destroyable ) || null;
  94. if ( ( !meta ) &amp;&amp; ( _create === true ) )
  95. _map.set( _destroyable, meta = new MetaData() );
  96. return meta;
  97. };
  98. /**
  99. * Remove MetaData for a Destroyable.
  100. * @param {module:barejs.Destroyable} _destroyable The Destroyable instance
  101. * @returns {module:barejs.Destroyable~MetaData} The removed meta data, or null
  102. */
  103. MetaData.remove = function( _destroyable )
  104. {
  105. var meta = _map.get( _destroyable ) || null;
  106. if ( meta )
  107. _map["delete"]( _destroyable );
  108. return meta;
  109. };
  110. }( new WeakMap() ) );
  111. /**
  112. * function that can be applied to an array to remove an item
  113. * @this {Array}
  114. * @memberof module:barejs.Destroyable~
  115. * @private
  116. */
  117. function Array_remove( _item )
  118. {
  119. /*jshint validthis:true*/
  120. var idx = this.indexOf( _item );
  121. /*istanbul ignore else: the if statement is purely a sanity check*/
  122. if ( idx >= 0 )
  123. this.splice( idx, 1 );
  124. return idx >= 0;
  125. }
  126. /**
  127. * Helper function that will destroy _target, if it is not null/undefined.
  128. * @param {module:barejs.Destroyable} _target The target to destroy.
  129. * @memberof module:barejs.Destroyable~
  130. * @private
  131. */
  132. function destroyTarget( _target/*, _index*/ )
  133. {
  134. if ( !_target )
  135. return;
  136. _target = Object( _target );
  137. if ( "destroy" in _target )
  138. _target.destroy();
  139. // Compatibility with dojo handles
  140. else if ( "remove" in _target )
  141. _target.remove();
  142. }
  143. /**
  144. * @class module:barejs.Destroyable~OwnedHandle
  145. * @private
  146. * @classdesc Tracks an ownership and destroys links when needed
  147. */
  148. function OwnedHandle( _owner, _target )
  149. {
  150. this.owner = _owner;
  151. this.target = _target;
  152. _owner.addDestroyListener( this._owner_destroyed = this._owner_destroyed.bind( this ) );
  153. if ( this.target instanceof Destroyable )
  154. this.target.addDestroyListener( this._target_destroyed = this._target_destroyed.bind( this ) );
  155. }
  156. decl.declareClass( OwnedHandle,
  157. /** @lends module:barejs.Destroyable~OwnedHandle# */
  158. {
  159. owner: null,
  160. target: null,
  161. _owner_destroyed: function()
  162. {
  163. /*istanbul ignore next: We actively remove listeners on destroy, so we don't expect to hit this safety guard*/
  164. if ( !this.target )
  165. return;
  166. // Destroyable::ref will take care of deleting any reference to this object
  167. // By deleting the owner before calling destroy, we are sure _target_destroyed will not
  168. // perform any logic
  169. delete this.owner;
  170. // We are about to call destroy, so there's no point in getting the notification
  171. if ( this.target instanceof Destroyable )
  172. this.target.removeDestroyListener( this._target_destroyed );
  173. destroyTarget( this.target );
  174. delete this._owner_destroyed;
  175. delete this._target_destroyed;
  176. delete this.target;
  177. },
  178. _target_destroyed: function()
  179. {
  180. /*istanbul ignore next: We actively remove listeners on destroy, so we don't expect to hit this safety guard*/
  181. if ( !this.owner )
  182. return;
  183. this.owner.removeDestroyListener( this._owner_destroyed );
  184. delete this._owner_destroyed;
  185. delete this._target_destroyed;
  186. delete this.owner;
  187. delete this.target;
  188. }
  189. } );
  190. /**
  191. * @class module:barejs.Destroyable
  192. * @classdesc Class that adds lifetime management to JavaScript objects. Destroyable provides a few features to ensure
  193. * the JavaScript garbage collector can recollect memory as soon as possible.
  194. *
  195. * A Destroyable instance can own other objects. The ownership in this case implies: if this instance is destroyed,
  196. * the instance I own should also be destroyed. Destroyable can own any object having either a destroy or remove method.
  197. *
  198. * A Destroyable instance can also ref other objects. The reference is automatically cleared on destroy. If the ref-ed
  199. * object is a Destroyable, the reference is also cleared if the target gets destroyed.
  200. *
  201. * Owned objects are also destroyed if this Destroyable is destroyed.
  202. * Referenced objects are automatically unlinked if this object is destroyed, and even if the referenced
  203. * is destroyed (in case the referenced object is Destroyable).
  204. */
  205. function Destroyable()
  206. {
  207. /*istanbul ignore else: We always test in DEBUG*/
  208. if ( !__RELEASE__ )
  209. Destroyable.alive.add( this );
  210. }
  211. DestroyableKey = decl.preventCast( Destroyable );
  212. // Protected hidden functions of Destroyable
  213. /**
  214. * Code that actually ties a target to an owner
  215. * @param {module:barejs.Destroyable} _target The target to own
  216. * @this {module:barejs.Destroyable}
  217. * @memberof module:barejs.Destroyable~
  218. * @private
  219. */
  220. function __own( _target/*used as iterator callback*/ )
  221. {
  222. // jshint validthis:true
  223. var actualTarget = resolveTarget( _target );
  224. if ( !actualTarget || !( ( "destroy" in actualTarget ) || ( "remove" in actualTarget ) ) )
  225. throw new TypeError( "Cannot own; invalid value" );
  226. else if ( actualTarget === this )
  227. throw new Error( "An object cannot own itself" );
  228. // Note the use of the comma operator; we don't need to store a reference to the OwnedHandle instance,
  229. // it just needs to be created. Using the comma operator avoid jshint warnings about using new for side-effects.
  230. return new OwnedHandle( this, actualTarget ), _target;
  231. }
  232. // Static array to track created Destroyable objects that haven't been destroyed yet
  233. /*istanbul ignore else: We always test in DEBUG*/
  234. if ( !__RELEASE__ )
  235. decl.defineProperty( Destroyable, "alive", { value: new WeakSet() } );
  236. // All methods of Destroyable are non-enumerable and protected from modification
  237. return decl.declareClass( Destroyable,
  238. /** @lends module:barejs.Destroyable */
  239. {
  240. // Don't inherit static alive/isDestroyed values
  241. $private:
  242. {
  243. value: function( _key )
  244. {
  245. return _key === "isDestroyed" || _key === "alive";
  246. }
  247. },
  248. // Protect isDestroyed method from tampering. We're not exposing this on instance level since it's
  249. // not a common operation.
  250. isDestroyed: { value: isDestroyed }
  251. },
  252. /** @lends module:barejs.Destroyable# */
  253. {
  254. /**
  255. * Destroy method that will notify registered listeners and clean up references.
  256. * @function
  257. */
  258. destroy:
  259. {
  260. // Subclasses must be able to add custom destroy logic, so allow writing destroy
  261. writable: true,
  262. value: function destroy()
  263. {
  264. if ( isDestroyed( this ) )
  265. return;
  266. var meta = MetaData.remove( this ), i, len;
  267. if ( meta )
  268. {
  269. // Invoke listeners before clearing references, in case listeners need to look at them
  270. if ( meta.listeners.length > 0 )
  271. {
  272. for ( i = 0, len = meta.listeners.length; i &lt; len; ++i )
  273. meta.listeners[i]( this );
  274. // Also explicitly clear the array to drop references to listeners
  275. meta.listeners.length = 0;
  276. }
  277. // Clear references
  278. if ( meta.references.length > 0 )
  279. {
  280. // Don't call unref since it will mutate the references array
  281. for ( i = 0, len = meta.references.length; i &lt; len; ++i )
  282. {
  283. if ( meta.referenceHandlers[i] )
  284. resolveTarget( this[ meta.references[i] ] ).removeDestroyListener( meta.referenceHandlers[i] );
  285. delete this[ meta.references[i] ];
  286. }
  287. // Clear the arrays
  288. meta.references.length = 0;
  289. meta.referenceHandlers.length = 0;
  290. }
  291. }
  292. /*istanbul ignore else: We always test in DEBUG*/
  293. if ( !__RELEASE__ )
  294. Destroyable.alive["delete"]( this );
  295. DestroyedObjects.add( this );
  296. }
  297. },
  298. /**
  299. * Register a destroy listener for this Destroyable object.
  300. * @function
  301. * @param {module:barejs.Destroyable~DestroyListener} _listener The listener function to add.
  302. * @returns {function} the listener
  303. */
  304. addDestroyListener:
  305. {
  306. value: function addDestroyListener( _listener )
  307. {
  308. var meta = MetaData.get( this, true );
  309. meta.listeners.push( ObjectPolyfill.ensureCallable( _listener ) );
  310. return _listener;
  311. }
  312. },
  313. /**
  314. * Unregister a destroy listener for this Destroyable object.
  315. * @function
  316. * @param {module:barejs.Destroyable~DestroyListener} _listener The listener function to remove.
  317. */
  318. removeDestroyListener:
  319. {
  320. value: function removeDestroyListener( _listener )
  321. {
  322. var meta = MetaData.get( this, false );
  323. return ( !!meta ) &amp;&amp; Array_remove.call( meta.listeners, _listener );
  324. }
  325. },
  326. /**
  327. * Own a number of handles. Returns an array of the owned handles.
  328. * @function
  329. * @returns {Array} The owned handles.
  330. */
  331. own:
  332. {
  333. value: function own( /*...*/ )
  334. {
  335. return map.call( arguments, __own, this );
  336. }
  337. },
  338. /**
  339. * Reference a target as a member property that will be unlinked on destroy.
  340. * If the referenced target is also Destroyable, the ref is also cleared if the target is destroyed.
  341. * @function
  342. * @param {string} _name The name to reference.
  343. * @param {object} _target The object to assign to the reference.
  344. * @returns The value of this[_name].
  345. */
  346. ref:
  347. {
  348. value: function ref( _name, _target )
  349. {
  350. if ( typeof _name !== "string" )
  351. throw new TypeError( "Name must be a string" );
  352. // typeof null === "object", but we don't want to allow it
  353. switch ( _target === null ? "undefined" : typeof _target )
  354. {
  355. // Functions can create a circular reference via closures (or being bound to this).
  356. case "function":
  357. // Referencing objects might cause circular references
  358. case "object":
  359. // So we allow referencing them
  360. break;
  361. case "undefined":
  362. throw new TypeError( "_target cannot be " + _target + ". Use unref to clear a reference." );
  363. default:
  364. throw new TypeError( "_target cannot be " + ( typeof _target ) + ". Only objects or functions can be referenced." );
  365. }
  366. var meta = MetaData.get( this, true ),
  367. idx = meta.references.indexOf( _name ),
  368. actualTarget;
  369. if ( idx &lt; 0 ) // Add reference
  370. {
  371. idx = meta.references.push( _name ) - 1;
  372. meta.referenceHandlers.push( null );
  373. }
  374. else if ( meta.referenceHandlers[idx] ) // Update/change reference
  375. {
  376. actualTarget = resolveTarget( this[_name] );
  377. if ( actualTarget instanceof Destroyable )
  378. actualTarget.removeDestroyListener( meta.referenceHandlers[idx] );
  379. meta.referenceHandlers[idx] = null;
  380. }
  381. decl.defineProperty( this, _name,
  382. {
  383. configurable: true,
  384. enumerable: ObjectPolyfill.shouldBeEnumerable( _name ),
  385. value: _target
  386. } );
  387. actualTarget = resolveTarget( _target );
  388. // If the thing we are referencing is a Destroyable, ensure it is unref-ed if the target gets destroyed.
  389. if ( actualTarget instanceof Destroyable )
  390. actualTarget.addDestroyListener( meta.referenceHandlers[idx] = this.unref.bind( this, _name ) );
  391. return _target;
  392. }
  393. },
  394. /**
  395. * Remove a reference (by name). If the name was given to ownMember, the member is NOT
  396. * removed from the list of owned targets.
  397. * Does NOT destroy the value currently referenced.
  398. * @function
  399. * @param {string} _name the name to remove the reference to
  400. * @param {object|function} [_value] If a value is provided (and is not null), unref will only clear the reference if _value equals whatever is currently ref-ed.
  401. */
  402. unref:
  403. {
  404. value: function unref( _name )
  405. {
  406. if ( typeof _name !== "string" )
  407. throw new TypeError( "_name must be a string" );
  408. var result/* = undefined*/, value = arguments[1], meta, idx, handler;
  409. if ( ( meta = MetaData.get( this, false ) ) &amp;&amp; ( ( idx = meta.references.indexOf( _name ) ) >= 0 ) )
  410. {
  411. result = this[ meta.references[idx] ];
  412. // If a second argument is supplied, we validate it equals the value to unref
  413. if ( value &amp;&amp; !decl.is( result, value ) )
  414. {
  415. result = undefined; // value did not match
  416. }
  417. else
  418. {
  419. delete this[ meta.references.splice( idx, 1 )[0] ];
  420. // Since we splice the name, we need to splice the handlers too; otherwise the references and handlers will go out of sync.
  421. // If a "target" is provided, assume we got called as a destroy listener; in that case we don't unregister since we got here from that listener.
  422. if ( ( handler = meta.referenceHandlers.splice( idx, 1 )[0] ) &amp;&amp; ( !value ) )
  423. resolveTarget( result ).removeDestroyListener( handler );
  424. }
  425. }
  426. return result;
  427. }
  428. },
  429. /**
  430. * The ownMember function combines ref and own into 1 call. The target is owned and then ref-ed as _name.
  431. * @function
  432. * @param {string} _name The name of the member.
  433. * @param {module:barejs.Destroyable} _target The target to own.
  434. * @returns The owned _target
  435. */
  436. ownMember:
  437. {
  438. value: function ownMember( _name, _target )
  439. {
  440. // use __own directly since it avoids the overhead of Array.prototype.map
  441. // Also, call __own before ref, since it does some stricter validation.
  442. return this.ref( _name, __own.call( this, _target ) );
  443. }
  444. },
  445. /**
  446. * Utility method that will iterate a collection and destroy all items in it.
  447. * @function
  448. * @param {object} _collection An object with a forEach method or length property (e.g. an Array).
  449. */
  450. destroyAll:
  451. {
  452. value: function destroyAll( _collection )
  453. {
  454. var c = Object( _collection );
  455. if ( "forEach" in c )
  456. c.forEach( destroyTarget, null );
  457. else if ( "length" in c )
  458. Array.prototype.forEach.call( c, destroyTarget, null );
  459. else
  460. throw new TypeError( "_collection must either have a forEach method or a length property." );
  461. }
  462. }
  463. } );
  464. /**
  465. * Destroy listeners are called with one argument; the Destroyed object.
  466. * @callback module:barejs.Destroyable~DestroyListener
  467. * @param {module:barejs.Destroyable} _destroyed The Destroyable that got destroyed.
  468. */
  469. // End of module
  470. }(
  471. require( "./polyfill/Object" ),
  472. require( "./decl" ),
  473. require( "./WeakMap" ),
  474. require( "./WeakSet" )
  475. ) );
  476. </code></pre>
  477. </article>
  478. </section>
  479. </div>
  480. <nav>
  481. <h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="module-barejs.html">barejs</a></li><li><a href="module-barejs_polyfill.html">barejs/polyfill</a></li><li><a href="module-barejs_polyfill_Intl.html">barejs/polyfill/Intl</a></li></ul><h3>Classes</h3><ul><li><a href="module-barejs.decl.html">decl</a></li><li><a href="module-barejs.decl-Enum.html">Enum</a></li><li><a href="module-barejs.decl-Interface.html">Interface</a></li><li><a href="module-barejs.decl-SpecialType.html">SpecialType</a></li><li><a href="module-barejs.Destroyable.html">Destroyable</a></li><li><a href="module-barejs.EventArgs.html">EventArgs</a></li><li><a href="module-barejs.Evented.html">Evented</a></li><li><a href="module-barejs.Evented-EventedHandle.html">EventedHandle</a></li><li><a href="module-barejs.Exception.html">Exception</a></li><li><a href="module-barejs_polyfill.Array.html">Array</a></li><li><a href="module-barejs_polyfill.Date.html">Date</a></li><li><a href="module-barejs_polyfill.EntryStore.html">EntryStore</a></li><li><a href="module-barejs_polyfill.EntryStore.Iterator.html">Iterator</a></li><li><a href="module-barejs_polyfill.Function.html">Function</a></li><li><a href="module-barejs_polyfill.Map.html">Map</a></li><li><a href="module-barejs_polyfill.Map-MapIterator.html">MapIterator</a></li><li><a href="module-barejs_polyfill.Math.html">Math</a></li><li><a href="module-barejs_polyfill.Number.html">Number</a></li><li><a href="module-barejs_polyfill.Object.html">Object</a></li><li><a href="module-barejs_polyfill.Promise.html">Promise</a></li><li><a href="module-barejs_polyfill.Set.html">Set</a></li><li><a href="module-barejs_polyfill.Set-SetIterator.html">SetIterator</a></li><li><a href="module-barejs_polyfill.String.html">String</a></li><li><a href="module-barejs_polyfill.Symbol.html">Symbol</a></li><li><a href="module-barejs_polyfill.WeakMap.html">WeakMap</a></li><li><a href="module-barejs_polyfill.WeakSet.html">WeakSet</a></li><li><a href="module-barejs_polyfill_Intl.DateTimeFormat.html">DateTimeFormat</a></li><li><a href="module-barejs_polyfill_Intl.DateTimeFormat-DateTimeFormatOptions.html">DateTimeFormatOptions</a></li><li><a href="module-barejs_polyfill_Intl.NumberFormat.html">NumberFormat</a></li><li><a href="module-barejs_polyfill_Intl.NumberFormat-NumberFormatOptions.html">NumberFormatOptions</a></li><li><a href="module-barejs_polyfill_Intl-Format.html">Format</a></li></ul>
  482. </nav>
  483. <br class="clear">
  484. <footer>
  485. Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a> on Wed Oct 03 2018 15:59:33 GMT+0200 (W. Europe Daylight Time)
  486. </footer>
  487. <script> prettyPrint(); </script>
  488. <script src="scripts/linenumber.js"> </script>
  489. </body>
  490. </html>