How do I create a custom event class in Javascript?

混江龙づ霸主 提交于 2019-12-17 17:44:46

问题


How do I create a custom event class similar to ActionScript? What I mean by that is a class that I can use to fire off my own events, send the necessary data.

I don't wanna use third-party libraries like YUI or jQuery to do it. My goal is to be able to send a event that looks like this.

document.addEventListener("customEvent", eventHandler, false);

function eventHandler(e){
    alert(e.para1);
}

document.dispatchEvent(new CustomEvent("customEvent", para1, para2));

Please no third-party library solutions.


回答1:


A method that worked for me was to call document.createEvent(), init it and dispatch it with window.dispatchEvent().

  var event = document.createEvent("Event");
  event.initEvent("customEvent", true, true);
  event.customData = getYourCustomData();
  window.dispatchEvent(event);



回答2:


I'm a little late to the party here, but was searching for the same thing. I'm not keen on the first answer (above) because it relies upon the document to manage the custom event. This is dangerous because it's global and could potentially conflict with another script should that script coincidentally rely on the same custom event.

The best solution I've found is here: Nicholas C. Zakas - Custom Events in Javascript

Unfortunately, since javascript doesn't support inheritance keywords, it's a bit messy with prototyping, but it definitely keeps things tidy.




回答3:


This is straightforward when using DOM elements to broker the events.

Given an element:

var element = document.querySelector('div#rocket');

For a client to subscribe:

element.addEventListener('liftoff', function(e)
{
    console.log('We have liftoff!');
});

Then to dispatch/raise/fire the event, use this code:

element.dispatch(new Event('liftoff'));



回答4:


This by John Resig:

function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}
function removeEvent( obj, type, fn ) {
  if ( obj.detachEvent ) {
    obj.detachEvent( 'on'+type, obj[type+fn] );
    obj[type+fn] = null;
  } else
    obj.removeEventListener( type, fn, false );
}

More at his blog post at http://ejohn.org/projects/flexible-javascript-events/.




回答5:


I was just thinking of assigning a supported handler to a new namespace i.e. a reference to a supported event. The code below works (paste it in console of Chrome) but you can write it in a better format, and you should have additional helper methods (that can redefine themselves as well), for xBrowser support, and for sniffing support types (which after you've detected which path to use, you'll have the function redefine itself. I hope what I have below helps.

var de = document.documentElement || document.getElementsByTagName[0];

function all(){ console.log('all') };

var customEventForSomeSpecificElement = function customEventForSomeSpecificElement() {
    return ({
            customEvent: function() {
                if ('onclick' in de ) {
                    return 'click';
                }
            },
            init: function(){ return this.customEvent(); }
        }).init();
}();

de.addEventListener(customEventForSomeSpecificElement, all, false);



回答6:


It's not so hard actually - there isn't so many event definitions, only three versions. The first one is the corect one (addEventListener), then there's the IE way (attachEvent) and then there's the compatibility way for older browser (element.onevent = function)

So a complete event handling solution would look something like this:

setEvent = function(element, eventName, handler){
  if('addEventListener' in element){
    //W3
    element.addEventListener(eventName,handler,false);
  }else if('attachEvent' in elm){
    //IE
    elm.attachEvent('on'+eventName,handler)
  }else{
    // compatibility
    elm['on'+eventName] = handler;
  }
}

and to clear events:

clearEvent = function(element, eventName, handler){
  if('removeEventListener' in element){
    //W3
    element.removeEventListener(eventName,handler,false);
  }else if('detachEvent' in elm){
    //IE
    elm.detachEvent('on'+eventName,handler)
  }else{
    // compatibility
    elm['on'+eventName] = null;
  }
}

and an example:

setEvent(document, "click", function(){alert('hello world!');});
clearEvent(document, "click", function(){alert('hello world!');});

This is not really a complete example though since the compatibility handler always overwrites the previous events (it's not appending actions, it's overwriting) so you probably would like to check if a handler is already set and then save it into some temporary variable and fire it inside the event handler function.



来源:https://stackoverflow.com/questions/2059456/how-do-i-create-a-custom-event-class-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!