为什么使用MooTools定义伪事件时Firefox中的事件是未定义的?

Why is event in Firefox undefined when defining a pseudo event with MooTools?

本文关键字:事件 未定义 Firefox MooTools 定义 为什么      更新时间:2023-09-26

我试图用MooTools定义一个伪事件。它可以在Chromium中工作,但在Firefox中不行。这两款浏览器都是最新的稳定版本。这是我的事件:

DOMEvent.definePseudo('ctrl', function(split, fn, args){
    if(event.ctrlKey == true) fn.apply(this, args); // this is where Firefox says undefined
});

如果在单击元素时按下crtl键,则应该触发。我是这样添加事件的:

this.element.addEvent('click:ctrl', function(event) {
    event.stop();
    data = this.retrieve('imageData');
    this.toggleClass('selected');
    if(this.hasClass('selected')) {
        gallery.collection[data.id] = data;
    } else {
        Object.erase(gallery.collection, data.id);
    }
});

有什么提示或想法为什么这个错误发生?我的想法是,我不通过event,但我不知道如何做到这一点,因为我的代码是在铬和其他浏览器工作。

如果您检查DOMEvent.definePseudo函数中的参数,您将看到没有event对象,而是args数组,其中事件对象是该数组的第一个元素。所以不是:

if (event。ctrlKey == true) fn。应用(这个,args);

应:

如果(args[0]。Control == true)应用(这个,args);

事件对象通常作为第一个参数传递给事件处理程序,而definePseudo实际上是事件处理程序的处理程序,您应该在其中决定事件处理程序将发生什么。你的代码在Chrome(也支持IE, Safari和Opera)上工作的原因是因为他们总是提供一个全局事件变量,但在Firefox中,你需要将事件对象作为参数传递给事件处理程序。

添加额外的自定义事件,如control+click,也可以很容易地实现Element.Events:

Element.Events.controlclick = {
    base: 'click',  // the base event type
    condition: function(event){     //a function to perform additional checks
        return (event.control == true);   // this means the event is free to fire
    }
};
$('test').addEvent('controlclick', function(event){
    console.log( 'the user clicked the left mouse button while holding the control key');
});