API Docs for: 3.17.2
Show:

File: app/js/view-extensions/view-node-map.js

  1. /**
  2. View extension that adds a static `getByNode()` method that returns the nearest
  3. View instance associated with the given Node (similar to Widget's `getByNode()`
  4. method).
  5.  
  6. @module app
  7. @submodule view-node-map
  8. @since 3.5.0
  9. **/
  10.  
  11. var buildCfg = Y.namespace('View._buildCfg'),
  12. instances = {};
  13.  
  14. /**
  15. View extension that adds a static `getByNode()` method that returns the nearest
  16. View instance associated with the given Node (similar to Widget's `getByNode()`
  17. method).
  18.  
  19. Note that it's important to call `destroy()` on a View instance using this
  20. extension when you plan to stop using it. This ensures that all internal
  21. references to that View are cleared to prevent memory leaks.
  22.  
  23. @class View.NodeMap
  24. @extensionfor View
  25. @since 3.5.0
  26. **/
  27. function NodeMap() {}
  28.  
  29. // Tells Base.create() to mix the static getByNode method into built classes.
  30. // We're cheating and modifying Y.View here, because right now there's no better
  31. // way to do it.
  32. buildCfg.aggregates || (buildCfg.aggregates = []);
  33. buildCfg.aggregates.push('getByNode');
  34.  
  35. /**
  36. Returns the nearest View instance associated with the given Node. The Node may
  37. be a View container or any child of a View container.
  38.  
  39. Note that only instances of Views that have the Y.View.NodeMap extension mixed
  40. in will be returned. The base View class doesn't provide this functionality by
  41. default due to the additional memory management overhead involved in maintaining
  42. a mapping of Nodes to View instances.
  43.  
  44. @method getByNode
  45. @param {Node|HTMLElement|String} node Node instance, selector string, or
  46. HTMLElement.
  47. @return {View} Closest View instance associated with the given Node, or `null`
  48. if no associated View instance was found.
  49. @static
  50. @since 3.5.0
  51. **/
  52. NodeMap.getByNode = function (node) {
  53. var view;
  54.  
  55. Y.one(node).ancestor(function (ancestor) {
  56. return (view = instances[Y.stamp(ancestor, true)]) || false;
  57. }, true);
  58.  
  59. return view || null;
  60. };
  61.  
  62. // To make this testable.
  63. NodeMap._instances = instances;
  64.  
  65. NodeMap.prototype = {
  66. initializer: function () {
  67. instances[Y.stamp(this.get('container'))] = this;
  68. },
  69.  
  70. destructor: function () {
  71. var stamp = Y.stamp(this.get('container'), true);
  72.  
  73. if (stamp in instances) {
  74. delete instances[stamp];
  75. }
  76. }
  77. };
  78.  
  79. Y.View.NodeMap = NodeMap;
  80.