|
1 /** |
|
2 * EventUtils.js |
|
3 * |
|
4 * Copyright, Moxiecode Systems AB |
|
5 * Released under LGPL License. |
|
6 * |
|
7 * License: http://www.tinymce.com/license |
|
8 * Contributing: http://www.tinymce.com/contributing |
|
9 */ |
|
10 |
|
11 /*jshint loopfunc:true*/ |
|
12 /*eslint no-loop-func:0 */ |
|
13 |
|
14 /** |
|
15 * This class wraps the browsers native event logic with more convenient methods. |
|
16 * |
|
17 * @class tinymce.dom.EventUtils |
|
18 */ |
|
19 define("tinymce/dom/EventUtils", [], function() { |
|
20 "use strict"; |
|
21 |
|
22 var eventExpandoPrefix = "mce-data-"; |
|
23 var mouseEventRe = /^(?:mouse|contextmenu)|click/; |
|
24 var deprecated = {keyLocation: 1, layerX: 1, layerY: 1, returnValue: 1}; |
|
25 |
|
26 /** |
|
27 * Binds a native event to a callback on the speified target. |
|
28 */ |
|
29 function addEvent(target, name, callback, capture) { |
|
30 if (target.addEventListener) { |
|
31 target.addEventListener(name, callback, capture || false); |
|
32 } else if (target.attachEvent) { |
|
33 target.attachEvent('on' + name, callback); |
|
34 } |
|
35 } |
|
36 |
|
37 /** |
|
38 * Unbinds a native event callback on the specified target. |
|
39 */ |
|
40 function removeEvent(target, name, callback, capture) { |
|
41 if (target.removeEventListener) { |
|
42 target.removeEventListener(name, callback, capture || false); |
|
43 } else if (target.detachEvent) { |
|
44 target.detachEvent('on' + name, callback); |
|
45 } |
|
46 } |
|
47 |
|
48 /** |
|
49 * Normalizes a native event object or just adds the event specific methods on a custom event. |
|
50 */ |
|
51 function fix(originalEvent, data) { |
|
52 var name, event = data || {}, undef; |
|
53 |
|
54 // Dummy function that gets replaced on the delegation state functions |
|
55 function returnFalse() { |
|
56 return false; |
|
57 } |
|
58 |
|
59 // Dummy function that gets replaced on the delegation state functions |
|
60 function returnTrue() { |
|
61 return true; |
|
62 } |
|
63 |
|
64 // Copy all properties from the original event |
|
65 for (name in originalEvent) { |
|
66 // layerX/layerY is deprecated in Chrome and produces a warning |
|
67 if (!deprecated[name]) { |
|
68 event[name] = originalEvent[name]; |
|
69 } |
|
70 } |
|
71 |
|
72 // Normalize target IE uses srcElement |
|
73 if (!event.target) { |
|
74 event.target = event.srcElement || document; |
|
75 } |
|
76 |
|
77 // Calculate pageX/Y if missing and clientX/Y available |
|
78 if (originalEvent && mouseEventRe.test(originalEvent.type) && originalEvent.pageX === undef && originalEvent.clientX !== undef) { |
|
79 var eventDoc = event.target.ownerDocument || document; |
|
80 var doc = eventDoc.documentElement; |
|
81 var body = eventDoc.body; |
|
82 |
|
83 event.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - |
|
84 (doc && doc.clientLeft || body && body.clientLeft || 0); |
|
85 |
|
86 event.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - |
|
87 (doc && doc.clientTop || body && body.clientTop || 0); |
|
88 } |
|
89 |
|
90 // Add preventDefault method |
|
91 event.preventDefault = function() { |
|
92 event.isDefaultPrevented = returnTrue; |
|
93 |
|
94 // Execute preventDefault on the original event object |
|
95 if (originalEvent) { |
|
96 if (originalEvent.preventDefault) { |
|
97 originalEvent.preventDefault(); |
|
98 } else { |
|
99 originalEvent.returnValue = false; // IE |
|
100 } |
|
101 } |
|
102 }; |
|
103 |
|
104 // Add stopPropagation |
|
105 event.stopPropagation = function() { |
|
106 event.isPropagationStopped = returnTrue; |
|
107 |
|
108 // Execute stopPropagation on the original event object |
|
109 if (originalEvent) { |
|
110 if (originalEvent.stopPropagation) { |
|
111 originalEvent.stopPropagation(); |
|
112 } else { |
|
113 originalEvent.cancelBubble = true; // IE |
|
114 } |
|
115 } |
|
116 }; |
|
117 |
|
118 // Add stopImmediatePropagation |
|
119 event.stopImmediatePropagation = function() { |
|
120 event.isImmediatePropagationStopped = returnTrue; |
|
121 event.stopPropagation(); |
|
122 }; |
|
123 |
|
124 // Add event delegation states |
|
125 if (!event.isDefaultPrevented) { |
|
126 event.isDefaultPrevented = returnFalse; |
|
127 event.isPropagationStopped = returnFalse; |
|
128 event.isImmediatePropagationStopped = returnFalse; |
|
129 } |
|
130 |
|
131 return event; |
|
132 } |
|
133 |
|
134 /** |
|
135 * Bind a DOMContentLoaded event across browsers and executes the callback once the page DOM is initialized. |
|
136 * It will also set/check the domLoaded state of the event_utils instance so ready isn't called multiple times. |
|
137 */ |
|
138 function bindOnReady(win, callback, eventUtils) { |
|
139 var doc = win.document, event = {type: 'ready'}; |
|
140 |
|
141 if (eventUtils.domLoaded) { |
|
142 callback(event); |
|
143 return; |
|
144 } |
|
145 |
|
146 // Gets called when the DOM is ready |
|
147 function readyHandler() { |
|
148 if (!eventUtils.domLoaded) { |
|
149 eventUtils.domLoaded = true; |
|
150 callback(event); |
|
151 } |
|
152 } |
|
153 |
|
154 function waitForDomLoaded() { |
|
155 // Check complete or interactive state if there is a body |
|
156 // element on some iframes IE 8 will produce a null body |
|
157 if (doc.readyState === "complete" || (doc.readyState === "interactive" && doc.body)) { |
|
158 removeEvent(doc, "readystatechange", waitForDomLoaded); |
|
159 readyHandler(); |
|
160 } |
|
161 } |
|
162 |
|
163 function tryScroll() { |
|
164 try { |
|
165 // If IE is used, use the trick by Diego Perini licensed under MIT by request to the author. |
|
166 // http://javascript.nwbox.com/IEContentLoaded/ |
|
167 doc.documentElement.doScroll("left"); |
|
168 } catch (ex) { |
|
169 setTimeout(tryScroll, 0); |
|
170 return; |
|
171 } |
|
172 |
|
173 readyHandler(); |
|
174 } |
|
175 |
|
176 // Use W3C method |
|
177 if (doc.addEventListener) { |
|
178 if (doc.readyState === "complete") { |
|
179 readyHandler(); |
|
180 } else { |
|
181 addEvent(win, 'DOMContentLoaded', readyHandler); |
|
182 } |
|
183 } else { |
|
184 // Use IE method |
|
185 addEvent(doc, "readystatechange", waitForDomLoaded); |
|
186 |
|
187 // Wait until we can scroll, when we can the DOM is initialized |
|
188 if (doc.documentElement.doScroll && win.self === win.top) { |
|
189 tryScroll(); |
|
190 } |
|
191 } |
|
192 |
|
193 // Fallback if any of the above methods should fail for some odd reason |
|
194 addEvent(win, 'load', readyHandler); |
|
195 } |
|
196 |
|
197 /** |
|
198 * This class enables you to bind/unbind native events to elements and normalize it's behavior across browsers. |
|
199 */ |
|
200 function EventUtils() { |
|
201 var self = this, events = {}, count, expando, hasFocusIn, hasMouseEnterLeave, mouseEnterLeave; |
|
202 |
|
203 expando = eventExpandoPrefix + (+new Date()).toString(32); |
|
204 hasMouseEnterLeave = "onmouseenter" in document.documentElement; |
|
205 hasFocusIn = "onfocusin" in document.documentElement; |
|
206 mouseEnterLeave = {mouseenter: 'mouseover', mouseleave: 'mouseout'}; |
|
207 count = 1; |
|
208 |
|
209 // State if the DOMContentLoaded was executed or not |
|
210 self.domLoaded = false; |
|
211 self.events = events; |
|
212 |
|
213 /** |
|
214 * Executes all event handler callbacks for a specific event. |
|
215 * |
|
216 * @private |
|
217 * @param {Event} evt Event object. |
|
218 * @param {String} id Expando id value to look for. |
|
219 */ |
|
220 function executeHandlers(evt, id) { |
|
221 var callbackList, i, l, callback, container = events[id]; |
|
222 |
|
223 callbackList = container && container[evt.type]; |
|
224 if (callbackList) { |
|
225 for (i = 0, l = callbackList.length; i < l; i++) { |
|
226 callback = callbackList[i]; |
|
227 |
|
228 // Check if callback exists might be removed if a unbind is called inside the callback |
|
229 if (callback && callback.func.call(callback.scope, evt) === false) { |
|
230 evt.preventDefault(); |
|
231 } |
|
232 |
|
233 // Should we stop propagation to immediate listeners |
|
234 if (evt.isImmediatePropagationStopped()) { |
|
235 return; |
|
236 } |
|
237 } |
|
238 } |
|
239 } |
|
240 |
|
241 /** |
|
242 * Binds a callback to an event on the specified target. |
|
243 * |
|
244 * @method bind |
|
245 * @param {Object} target Target node/window or custom object. |
|
246 * @param {String} names Name of the event to bind. |
|
247 * @param {function} callback Callback function to execute when the event occurs. |
|
248 * @param {Object} scope Scope to call the callback function on, defaults to target. |
|
249 * @return {function} Callback function that got bound. |
|
250 */ |
|
251 self.bind = function(target, names, callback, scope) { |
|
252 var id, callbackList, i, name, fakeName, nativeHandler, capture, win = window; |
|
253 |
|
254 // Native event handler function patches the event and executes the callbacks for the expando |
|
255 function defaultNativeHandler(evt) { |
|
256 executeHandlers(fix(evt || win.event), id); |
|
257 } |
|
258 |
|
259 // Don't bind to text nodes or comments |
|
260 if (!target || target.nodeType === 3 || target.nodeType === 8) { |
|
261 return; |
|
262 } |
|
263 |
|
264 // Create or get events id for the target |
|
265 if (!target[expando]) { |
|
266 id = count++; |
|
267 target[expando] = id; |
|
268 events[id] = {}; |
|
269 } else { |
|
270 id = target[expando]; |
|
271 } |
|
272 |
|
273 // Setup the specified scope or use the target as a default |
|
274 scope = scope || target; |
|
275 |
|
276 // Split names and bind each event, enables you to bind multiple events with one call |
|
277 names = names.split(' '); |
|
278 i = names.length; |
|
279 while (i--) { |
|
280 name = names[i]; |
|
281 nativeHandler = defaultNativeHandler; |
|
282 fakeName = capture = false; |
|
283 |
|
284 // Use ready instead of DOMContentLoaded |
|
285 if (name === "DOMContentLoaded") { |
|
286 name = "ready"; |
|
287 } |
|
288 |
|
289 // DOM is already ready |
|
290 if (self.domLoaded && name === "ready" && target.readyState == 'complete') { |
|
291 callback.call(scope, fix({type: name})); |
|
292 continue; |
|
293 } |
|
294 |
|
295 // Handle mouseenter/mouseleaver |
|
296 if (!hasMouseEnterLeave) { |
|
297 fakeName = mouseEnterLeave[name]; |
|
298 |
|
299 if (fakeName) { |
|
300 nativeHandler = function(evt) { |
|
301 var current, related; |
|
302 |
|
303 current = evt.currentTarget; |
|
304 related = evt.relatedTarget; |
|
305 |
|
306 // Check if related is inside the current target if it's not then the event should |
|
307 // be ignored since it's a mouseover/mouseout inside the element |
|
308 if (related && current.contains) { |
|
309 // Use contains for performance |
|
310 related = current.contains(related); |
|
311 } else { |
|
312 while (related && related !== current) { |
|
313 related = related.parentNode; |
|
314 } |
|
315 } |
|
316 |
|
317 // Fire fake event |
|
318 if (!related) { |
|
319 evt = fix(evt || win.event); |
|
320 evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter'; |
|
321 evt.target = current; |
|
322 executeHandlers(evt, id); |
|
323 } |
|
324 }; |
|
325 } |
|
326 } |
|
327 |
|
328 // Fake bubbeling of focusin/focusout |
|
329 if (!hasFocusIn && (name === "focusin" || name === "focusout")) { |
|
330 capture = true; |
|
331 fakeName = name === "focusin" ? "focus" : "blur"; |
|
332 nativeHandler = function(evt) { |
|
333 evt = fix(evt || win.event); |
|
334 evt.type = evt.type === 'focus' ? 'focusin' : 'focusout'; |
|
335 executeHandlers(evt, id); |
|
336 }; |
|
337 } |
|
338 |
|
339 // Setup callback list and bind native event |
|
340 callbackList = events[id][name]; |
|
341 if (!callbackList) { |
|
342 events[id][name] = callbackList = [{func: callback, scope: scope}]; |
|
343 callbackList.fakeName = fakeName; |
|
344 callbackList.capture = capture; |
|
345 //callbackList.callback = callback; |
|
346 |
|
347 // Add the nativeHandler to the callback list so that we can later unbind it |
|
348 callbackList.nativeHandler = nativeHandler; |
|
349 |
|
350 // Check if the target has native events support |
|
351 |
|
352 if (name === "ready") { |
|
353 bindOnReady(target, nativeHandler, self); |
|
354 } else { |
|
355 addEvent(target, fakeName || name, nativeHandler, capture); |
|
356 } |
|
357 } else { |
|
358 if (name === "ready" && self.domLoaded) { |
|
359 callback({type: name}); |
|
360 } else { |
|
361 // If it already has an native handler then just push the callback |
|
362 callbackList.push({func: callback, scope: scope}); |
|
363 } |
|
364 } |
|
365 } |
|
366 |
|
367 target = callbackList = 0; // Clean memory for IE |
|
368 |
|
369 return callback; |
|
370 }; |
|
371 |
|
372 /** |
|
373 * Unbinds the specified event by name, name and callback or all events on the target. |
|
374 * |
|
375 * @method unbind |
|
376 * @param {Object} target Target node/window or custom object. |
|
377 * @param {String} names Optional event name to unbind. |
|
378 * @param {function} callback Optional callback function to unbind. |
|
379 * @return {EventUtils} Event utils instance. |
|
380 */ |
|
381 self.unbind = function(target, names, callback) { |
|
382 var id, callbackList, i, ci, name, eventMap; |
|
383 |
|
384 // Don't bind to text nodes or comments |
|
385 if (!target || target.nodeType === 3 || target.nodeType === 8) { |
|
386 return self; |
|
387 } |
|
388 |
|
389 // Unbind event or events if the target has the expando |
|
390 id = target[expando]; |
|
391 if (id) { |
|
392 eventMap = events[id]; |
|
393 |
|
394 // Specific callback |
|
395 if (names) { |
|
396 names = names.split(' '); |
|
397 i = names.length; |
|
398 while (i--) { |
|
399 name = names[i]; |
|
400 callbackList = eventMap[name]; |
|
401 |
|
402 // Unbind the event if it exists in the map |
|
403 if (callbackList) { |
|
404 // Remove specified callback |
|
405 if (callback) { |
|
406 ci = callbackList.length; |
|
407 while (ci--) { |
|
408 if (callbackList[ci].func === callback) { |
|
409 var nativeHandler = callbackList.nativeHandler; |
|
410 var fakeName = callbackList.fakeName, capture = callbackList.capture; |
|
411 |
|
412 // Clone callbackList since unbind inside a callback would otherwise break the handlers loop |
|
413 callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1)); |
|
414 callbackList.nativeHandler = nativeHandler; |
|
415 callbackList.fakeName = fakeName; |
|
416 callbackList.capture = capture; |
|
417 |
|
418 eventMap[name] = callbackList; |
|
419 } |
|
420 } |
|
421 } |
|
422 |
|
423 // Remove all callbacks if there isn't a specified callback or there is no callbacks left |
|
424 if (!callback || callbackList.length === 0) { |
|
425 delete eventMap[name]; |
|
426 removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture); |
|
427 } |
|
428 } |
|
429 } |
|
430 } else { |
|
431 // All events for a specific element |
|
432 for (name in eventMap) { |
|
433 callbackList = eventMap[name]; |
|
434 removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture); |
|
435 } |
|
436 |
|
437 eventMap = {}; |
|
438 } |
|
439 |
|
440 // Check if object is empty, if it isn't then we won't remove the expando map |
|
441 for (name in eventMap) { |
|
442 return self; |
|
443 } |
|
444 |
|
445 // Delete event object |
|
446 delete events[id]; |
|
447 |
|
448 // Remove expando from target |
|
449 try { |
|
450 // IE will fail here since it can't delete properties from window |
|
451 delete target[expando]; |
|
452 } catch (ex) { |
|
453 // IE will set it to null |
|
454 target[expando] = null; |
|
455 } |
|
456 } |
|
457 |
|
458 return self; |
|
459 }; |
|
460 |
|
461 /** |
|
462 * Fires the specified event on the specified target. |
|
463 * |
|
464 * @method fire |
|
465 * @param {Object} target Target node/window or custom object. |
|
466 * @param {String} name Event name to fire. |
|
467 * @param {Object} args Optional arguments to send to the observers. |
|
468 * @return {EventUtils} Event utils instance. |
|
469 */ |
|
470 self.fire = function(target, name, args) { |
|
471 var id; |
|
472 |
|
473 // Don't bind to text nodes or comments |
|
474 if (!target || target.nodeType === 3 || target.nodeType === 8) { |
|
475 return self; |
|
476 } |
|
477 |
|
478 // Build event object by patching the args |
|
479 args = fix(null, args); |
|
480 args.type = name; |
|
481 args.target = target; |
|
482 |
|
483 do { |
|
484 // Found an expando that means there is listeners to execute |
|
485 id = target[expando]; |
|
486 if (id) { |
|
487 executeHandlers(args, id); |
|
488 } |
|
489 |
|
490 // Walk up the DOM |
|
491 target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow; |
|
492 } while (target && !args.isPropagationStopped()); |
|
493 |
|
494 return self; |
|
495 }; |
|
496 |
|
497 /** |
|
498 * Removes all bound event listeners for the specified target. This will also remove any bound |
|
499 * listeners to child nodes within that target. |
|
500 * |
|
501 * @method clean |
|
502 * @param {Object} target Target node/window object. |
|
503 * @return {EventUtils} Event utils instance. |
|
504 */ |
|
505 self.clean = function(target) { |
|
506 var i, children, unbind = self.unbind; |
|
507 |
|
508 // Don't bind to text nodes or comments |
|
509 if (!target || target.nodeType === 3 || target.nodeType === 8) { |
|
510 return self; |
|
511 } |
|
512 |
|
513 // Unbind any element on the specificed target |
|
514 if (target[expando]) { |
|
515 unbind(target); |
|
516 } |
|
517 |
|
518 // Target doesn't have getElementsByTagName it's probably a window object then use it's document to find the children |
|
519 if (!target.getElementsByTagName) { |
|
520 target = target.document; |
|
521 } |
|
522 |
|
523 // Remove events from each child element |
|
524 if (target && target.getElementsByTagName) { |
|
525 unbind(target); |
|
526 |
|
527 children = target.getElementsByTagName('*'); |
|
528 i = children.length; |
|
529 while (i--) { |
|
530 target = children[i]; |
|
531 |
|
532 if (target[expando]) { |
|
533 unbind(target); |
|
534 } |
|
535 } |
|
536 } |
|
537 |
|
538 return self; |
|
539 }; |
|
540 |
|
541 /** |
|
542 * Destroys the event object. Call this on IE to remove memory leaks. |
|
543 */ |
|
544 self.destroy = function() { |
|
545 events = {}; |
|
546 }; |
|
547 |
|
548 // Legacy function for canceling events |
|
549 self.cancel = function(e) { |
|
550 if (e) { |
|
551 e.preventDefault(); |
|
552 e.stopImmediatePropagation(); |
|
553 } |
|
554 |
|
555 return false; |
|
556 }; |
|
557 } |
|
558 |
|
559 EventUtils.Event = new EventUtils(); |
|
560 EventUtils.Event.bind(window, 'ready', function() {}); |
|
561 |
|
562 return EventUtils; |
|
563 }); |