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