EventUtils.js 16 KB

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