手动触发窗口对象上的事件 [英] Manually trigger an event on window object

查看:133
本文介绍了手动触发窗口对象上的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在像这样添加一个侦听器:

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

如何手动触发此事件?

编辑

我也尝试过:

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

但是该处理程序未与此一起运行,因为它未在jquery中注册...

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

推荐答案

如果通过jQuery触发事件,则该事件应该已经通过jQuery附加了-请参阅@fredericHamidi的评论.

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');

> 正在制作JSFIDDLE演示

或者,如果您使用的是普通香草JS,请按照以下方式进行操作:

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

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

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

> 正在运行JSFIDDLE演示

这篇关于手动触发窗口对象上的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆