How can I fire my own Javascript event from the QUnit test?

I am working on a Javascript library that is independent of jQuery, although I have jQuery and QUnit available in my tests. In the library, I attach an event to an element, as jQuery does:

if (document.addEventListener) { tab.addEventListener('click', MyModule.show, false); } else if (document.attachEvent) { tab.attachEvent('click', MyModule.show); } 

I tried calling $('#tab').click(); to your QUnit test, but this does not call the event handler.

+4
source share
2 answers

jQuery has its own event logging system, which is separate from DOM event logging. When we call $(something).click() , all registered jQuery handlers and registered onclick handlers will start, but nothing else will happen. For instance,

 document.body.addEventListener('click', function() { alert('event') }, false); document.body.onclick = function() { alert('onclick'); }; $('body').click(); // alerts "onclick" 

If you call document.body.onclick() , then only the second event and "onclick" will fire. To trigger both events, create an event object and send it for the considered element - the body in this case. You can find it here . Unsurprisingly, IE uses a different mechanism to do the same, and you need to call fireEvent .

Here's an example of a non-cross browser for modern browsers (taken from the MDC article above),

 var clickEvent = document.createEvent('MouseEvents'); clickEvent.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); document.body.dispatchEvent(clickEvent); 
+12
source

(not sure) jQuery uses its own event system on top of its own event system. $(el).click() is called directly in this event system, and not in its own system. (/not sure)

 document.getElementById('tab').onclick(); 

Is the native equivalent, but you can first check if the item request actually finds this item. Do you initialize QUnit tests when dom is ready?

Also, for attachEvent (IE) you need an event prefix with 'on'.

 tab.attachEvent('onclick', listenerFn); 

ps. in fact, I believe that the missing 'on' prefix for the IE equivalent was a problem. Change it and check $ () again. Click () again.

+1
source

All Articles