Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / src / core / src / dom / Element-more.js
1 /**
2  * @class Ext.core.Element
3  */
4
5 Ext.core.Element.addMethods({
6
7     /**
8      * Monitors this Element for the mouse leaving. Calls the function after the specified delay only if
9      * the mouse was not moved back into the Element within the delay. If the mouse <i>was</i> moved
10      * back in, the function is not called.
11      * @param {Number} delay The delay <b>in milliseconds</b> to wait for possible mouse re-entry before calling the handler function.
12      * @param {Function} handler The function to call if the mouse remains outside of this Element for the specified time.
13      * @param {Object} scope The scope (<code>this</code> reference) in which the handler function executes. Defaults to this Element.
14      * @return {Object} The listeners object which was added to this element so that monitoring can be stopped. Example usage:</pre><code>
15 // Hide the menu if the mouse moves out for 250ms or more
16 this.mouseLeaveMonitor = this.menuEl.monitorMouseLeave(250, this.hideMenu, this);
17
18 ...
19 // Remove mouseleave monitor on menu destroy
20 this.menuEl.un(this.mouseLeaveMonitor);
21 </code></pre>
22      */
23     monitorMouseLeave: function(delay, handler, scope) {
24         var me = this,
25             timer,
26             listeners = {
27                 mouseleave: function(e) {
28                     timer = setTimeout(Ext.Function.bind(handler, scope||me, [e]), delay);
29                 },
30                 mouseenter: function() {
31                     clearTimeout(timer);
32                 },
33                 freezeEvent: true
34             };
35
36         me.on(listeners);
37         return listeners;
38     },
39
40     /**
41      * Stops the specified event(s) from bubbling and optionally prevents the default action
42      * @param {String/Array} eventName an event / array of events to stop from bubbling
43      * @param {Boolean} preventDefault (optional) true to prevent the default action too
44      * @return {Ext.core.Element} this
45      */
46     swallowEvent : function(eventName, preventDefault) {
47         var me = this;
48         function fn(e) {
49             e.stopPropagation();
50             if (preventDefault) {
51                 e.preventDefault();
52             }
53         }
54         
55         if (Ext.isArray(eventName)) {
56             Ext.each(eventName, function(e) {
57                  me.on(e, fn);
58             });
59             return me;
60         }
61         me.on(eventName, fn);
62         return me;
63     },
64
65     /**
66      * Create an event handler on this element such that when the event fires and is handled by this element,
67      * it will be relayed to another object (i.e., fired again as if it originated from that object instead).
68      * @param {String} eventName The type of event to relay
69      * @param {Object} object Any object that extends {@link Ext.util.Observable} that will provide the context
70      * for firing the relayed event
71      */
72     relayEvent : function(eventName, observable) {
73         this.on(eventName, function(e) {
74             observable.fireEvent(eventName, e);
75         });
76     },
77
78     /**
79      * Removes Empty, or whitespace filled text nodes. Combines adjacent text nodes.
80      * @param {Boolean} forceReclean (optional) By default the element
81      * keeps track if it has been cleaned already so
82      * you can call this over and over. However, if you update the element and
83      * need to force a reclean, you can pass true.
84      */
85     clean : function(forceReclean) {
86         var me  = this,
87             dom = me.dom,
88             n   = dom.firstChild,
89             nx,
90             ni  = -1;
91
92         if (Ext.core.Element.data(dom, 'isCleaned') && forceReclean !== true) {
93             return me;
94         }
95
96         while (n) {
97             nx = n.nextSibling;
98             if (n.nodeType == 3) {
99                 // Remove empty/whitespace text nodes
100                 if (!(/\S/.test(n.nodeValue))) {
101                     dom.removeChild(n);
102                 // Combine adjacent text nodes
103                 } else if (nx && nx.nodeType == 3) {
104                     n.appendData(Ext.String.trim(nx.data));
105                     dom.removeChild(nx);
106                     nx = n.nextSibling;
107                     n.nodeIndex = ++ni;
108                 }
109             } else {
110                 // Recursively clean
111                 Ext.fly(n).clean();
112                 n.nodeIndex = ++ni;
113             }
114             n = nx;
115         }
116
117         Ext.core.Element.data(dom, 'isCleaned', true);
118         return me;
119     },
120
121     /**
122      * Direct access to the Ext.ElementLoader {@link Ext.ElementLoader#load} method. The method takes the same object
123      * parameter as {@link Ext.ElementLoader#load}
124      * @return {Ext.core.Element} this
125      */
126     load : function(options) {
127         this.getLoader().load(options);
128         return this;
129     },
130
131     /**
132     * Gets this element's {@link Ext.ElementLoader ElementLoader}
133     * @return {Ext.ElementLoader} The loader
134     */
135     getLoader : function() {
136         var dom = this.dom,
137             data = Ext.core.Element.data,
138             loader = data(dom, 'loader');
139             
140         if (!loader) {
141             loader = Ext.create('Ext.ElementLoader', {
142                 target: this
143             });
144             data(dom, 'loader', loader);
145         }
146         return loader;
147     },
148
149     /**
150     * Update the innerHTML of this element, optionally searching for and processing scripts
151     * @param {String} html The new HTML
152     * @param {Boolean} loadScripts (optional) True to look for and process scripts (defaults to false)
153     * @param {Function} callback (optional) For async script loading you can be notified when the update completes
154     * @return {Ext.core.Element} this
155      */
156     update : function(html, loadScripts, callback) {
157         var me = this,
158             id,
159             dom,
160             interval;
161             
162         if (!me.dom) {
163             return me;
164         }
165         html = html || '';
166         dom = me.dom;
167
168         if (loadScripts !== true) {
169             dom.innerHTML = html;
170             Ext.callback(callback, me);
171             return me;
172         }
173
174         id  = Ext.id();
175         html += '<span id="' + id + '"></span>';
176
177         interval = setInterval(function(){
178             if (!document.getElementById(id)) {
179                 return false;    
180             }
181             clearInterval(interval);
182             var DOC    = document,
183                 hd     = DOC.getElementsByTagName("head")[0],
184                 re     = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig,
185                 srcRe  = /\ssrc=([\'\"])(.*?)\1/i,
186                 typeRe = /\stype=([\'\"])(.*?)\1/i,
187                 match,
188                 attrs,
189                 srcMatch,
190                 typeMatch,
191                 el,
192                 s;
193
194             while ((match = re.exec(html))) {
195                 attrs = match[1];
196                 srcMatch = attrs ? attrs.match(srcRe) : false;
197                 if (srcMatch && srcMatch[2]) {
198                    s = DOC.createElement("script");
199                    s.src = srcMatch[2];
200                    typeMatch = attrs.match(typeRe);
201                    if (typeMatch && typeMatch[2]) {
202                        s.type = typeMatch[2];
203                    }
204                    hd.appendChild(s);
205                 } else if (match[2] && match[2].length > 0) {
206                     if (window.execScript) {
207                        window.execScript(match[2]);
208                     } else {
209                        window.eval(match[2]);
210                     }
211                 }
212             }
213             
214             el = DOC.getElementById(id);
215             if (el) {
216                 Ext.removeNode(el);
217             }
218             Ext.callback(callback, me);
219         }, 20);
220         dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, '');
221         return me;
222     },
223
224     // inherit docs, overridden so we can add removeAnchor
225     removeAllListeners : function() {
226         this.removeAnchor();
227         Ext.EventManager.removeAll(this.dom);
228         return this;
229     },
230
231     /**
232      * Creates a proxy element of this element
233      * @param {String/Object} config The class name of the proxy element or a DomHelper config object
234      * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
235      * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
236      * @return {Ext.core.Element} The new proxy element
237      */
238     createProxy : function(config, renderTo, matchBox) {
239         config = (typeof config == 'object') ? config : {tag : "div", cls: config};
240
241         var me = this,
242             proxy = renderTo ? Ext.core.DomHelper.append(renderTo, config, true) :
243                                Ext.core.DomHelper.insertBefore(me.dom, config, true);
244
245         proxy.setVisibilityMode(Ext.core.Element.DISPLAY);
246         proxy.hide();
247         if (matchBox && me.setBox && me.getBox) { // check to make sure Element.position.js is loaded
248            proxy.setBox(me.getBox());
249         }
250         return proxy;
251     }
252 });
253 Ext.core.Element.prototype.clearListeners = Ext.core.Element.prototype.removeAllListeners;