简体   繁体   中英

Manually trigger an event on window object

I am adding a listener like so:

    window.addEventListener('native.showkeyboard', function (e) {
        ...
        ...
    });

I'm writing a unit test for this so I want to trigger the event. Im doing:

    window.trigger('native.showkeyboard');

But I end up with an error for that line saying:

    undefined is not a function

How can I manually trigger this event?

EDIT

I have also tried:

  $(window).trigger('native.showkeyboard');

but the handler doesnt run with this as it's not registered with jquery...

If you are triggering the event via jQuery then the event ought to have been attached via jQuery -- see @fredericHamidi's comment.

$(window).on('native.showkeyboard', function (e) {
    .........
});

$(window).trigger('native.showkeyboard');

WORKING JSFIDDLE DEMO

Or if you're using plain vanilla JS do it this way:

window.addEventListener('native.showkeyboard', function (e) {
    ........
});

window.dispatchEvent( new Event('native.showkeyboard') );

WORKING JSFIDDLE DEMO

well you are not working with a jQuery object...That would be your problem.

 window.trigger('native.showkeyboard');  //<-- window is not a jQuery object

You need to wrap it

 $(window).trigger('native.showkeyboard');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM