Trigger an event with Prototype

2019-01-03 02:12发布

Does anybody know of a method to trigger an event in Prototype, as you can with jQuery's trigger function?

I have bound an event listener using the observe method, but I would also like to be able to fire the event programatically.

Thanks in advance

4条回答
霸刀☆藐视天下
2楼-- · 2019-01-03 02:56

I don't think there is one built in to Prototype, but you can use this (not tested but should at least get you in the right direction):

Element.prototype.triggerEvent = function(eventName)
{
    if (document.createEvent)
    {
        var evt = document.createEvent('HTMLEvents');
        evt.initEvent(eventName, true, true);

        return this.dispatchEvent(evt);
    }

    if (this.fireEvent)
        return this.fireEvent('on' + eventName);
}

$('foo').triggerEvent('mouseover');
查看更多
三岁会撩人
3楼-- · 2019-01-03 02:57

The answers here are true for "Normal" events, that is events which are defined by the User Agent, but for custom events you should use prototype's "fire" method. e.g.

$('something').observe('my:custom', function() { alert('Custom'); });
.
.
$('something').fire('my:custom'); // This will cause the alert to display
查看更多
smile是对你的礼貌
4楼-- · 2019-01-03 02:57

I found this post helpful... http://jehiah.cz/archive/firing-javascript-events-properly

It covers a way to fire events in both Firefox and IE.

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}
查看更多
▲ chillily
5楼-- · 2019-01-03 03:08

event.simulate.js fits your needs.

I've used this several times and it works like a charm. It allows you to manually trigger native events, such as click or hover like so:

$('foo').simulate('click');

The great thing about this is that all attached event handlers will still be executed, just as if you would have clicked the element yourself.

For custom events you can use the standard prototype method Event.fire().

查看更多
登录 后发表回答