MouseEventConstructor不是构造函数

时间:2017-03-21 14:15:48

标签: javascript constructor mouseevent qunit

当我在本地执行测试时,它们没有任何问题,但是当我在服务器上进行测试时,我得到了:

TypeError: MouseEventConstructor is not a constructor (evaluating 'new MouseEvent('mousedown',
EXEC : error : TypeError: MouseEventConstructor is not a constructor (evaluating 'new MouseEvent('mousedown', 
        {
            'which': 1,
            'view': window,
            'bubbles': true,
            'cancelable': true
        })')

代码:

HTMLElement.prototype.mouseDownLeftButton = function () {
        var event = new MouseEvent('mousedown',
        {
            'which': 1,
            'view': window,
            'bubbles': true,
            'cancelable': true
        });
        this.dispatchEvent(event);
    };

这完全没问题。有没有其他方法可以创建new MouseEvent

2 个答案:

答案 0 :(得分:4)

很可能你的本地测试infra使用真正的浏览器,而在服务器上它使用PhantomJS。

后者仍然不支持新的MouseEvent:https://github.com/ariya/phantomjs/issues/11289

我必须做以下技巧才能通过测试:

    function createMouseEvent(typeArg: string): MouseEvent {
        let event = document.createEvent('MouseEvent');
        event.initMouseEvent(typeArg,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined);
        return event;
    }

答案 1 :(得分:3)

来自MDN的polyfill将解决此问题:

https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent#Polyfill

(function (window) {
    try {
        new MouseEvent('test');
        return false; // No need to polyfill
    } catch (e) {
        // Need to polyfill - fall through
    }

    // Polyfills DOM4 MouseEvent

    var MouseEvent = function (eventType, params) {
        params = params || { bubbles: false, cancelable: false };
        var mouseEvent = document.createEvent('MouseEvent');
        mouseEvent.initMouseEvent(eventType, params.bubbles, params.cancelable, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

        return mouseEvent;
    };

    MouseEvent.prototype = Event.prototype;

    window.MouseEvent = MouseEvent;
})(window);