Detailed JavaScript to implement custom event _javascript tips

Source: Internet
Author: User

We usually use a series of browser-specific behavior events, such as Onclick,onmouseover, when we manipulate DOM.
Then the custom event, as the name suggests, is to define the event type yourself, define the event handler itself, and call which handler when the appropriate event type is required.

1.js Supported Browser Default events

Browser-specific behavior of the event, or call system events, JS default events and so on, you know what I mean on the line, hereinafter I call him JS default event.
JS Default Event binding, event removal, and so on a series of operations, I believe we have been useful, such as:

DOM0-level event handler
var odiv = document.getElementById (' Odiv ');
Odiv.onclick = function () {
  alert ("You clicked on Me");
}

Or

DOM2-level event handler
var odiv = document.getElementById (' Odiv ');

Non ie
odiv.addeventlistener ("click", Function () {
  alert ("You clicked Me");
},false); 

IE
odiv.attachevent ("onclick", function () {
  alert ("You clicked on Me");
};

All I do is not do too much research, after all, we come to discuss the JS custom event, here gives a I have previously encapsulated the processing JS default event code:

Cross-browser event handlers//calls directly with Domevent.addevent (,,), direct call//use, first add the event with Addevent, then write other function methods directly inside handlefun, such as getevent; AddEventListener and attachevent---are dom2-level event handlers var domevent = {//element:dom object, event: Pending events, Handlefun: handler function//event name, excluding "On", such as "click", "MouseOver", "KeyDown", etc. addevent:function (element,event,handlefun) {// 
    AddEventListener----applied to Mozilla if (Element.addeventlistener) {Element.addeventlistener (event,handlefun,false); 
    }//attachevent----applied to IE else if (element.attachevent) {element.attachevent ("on" +event,handlefun); 
      }//other Dom0-level event handlers else{//element.onclick===element["on" +event]; 
    element["on" +event] = Handlefun; },///event name, including "on", such as "onclick", "onmouseover", "onkeydown", Removeevent:function (element,event,handlefun) {//re Moveeventlistener----applied to the Mozilla if (Element.removeeventlistener) {Element.removeeventlistener (event,handlefun 
    , false); }//detachevent----applied to IE else if (element.dEtachevent) {element.detachevent ("on" +event,handlefun); 
    }//other Dom0-level event handlers else {element["on" +event] = null; 
    },//block event bubbling stoppropagation:function {if (event.stoppropagation) {event.stoppropagation (); }else{event.cancelbubble = true;//ie Block event bubbling, true stands for blocking},//block event default behavior preventdefault:function (even 
    T) {if (Event.preventdefault) {event.preventdefault (); }else{event.returnvalue = false;//ie Block event bubbling, false represents block},//Get event element//event.target--non ie//EVENT.SR 
  Celement--ie Getelement:function (event) {return Event.target | | event.srcelement; 
  },//Get events Getevent:function {return event event:window.event; 
  },//Get the event type Gettype:function (event) {return event.type; 
 } 
};

Next class we are not as good as the topic, JS custom events

2. Object Direct Volume Package JS custom Event

According to the package above, we can conceive

var eventtarget = {
  addevent:function () {/
    /Add Event
  },
  fireevent:function () {
    //triggering event
  },
  Removeevent:function () {
    //Remove Event
  }
};

Believe that everyone is better understood, and then there is a problem you can think of, that is, JS default event, JS can correspond to one by one, know that is that, then our custom event, this one by one corresponding mapping table can only we build, and then I like this

var eventtarget = {
  //Save map
  handlers:{},
  addevent:function () {
    //Process Code
  },
  fireEvent: function () {
    //Trigger code
  },
  removeevent:function () {
    //Remove Code
  }
};

This is how I built this mapping relationship.

Handlers = {"
  type1": [
    "Fun1",
    "fun2",
    ///"..."
  ],
  "type2": [
    "Fun1",
    " Fun2 "
    //" ... "
  ]
  //" ... "
}

So that each type can have more than one handler function, so that after we expand
Next is the code aspects of the actual combat, write the specific processing code ...

I'm sure you're already clear about this idea, I'll just attach the code.

Direct volume processing JS custom event var eventtarget = {//save event Type, handle function array map handlers:{},//register event handler for given type,//type-> custom event type, handler -> Custom Event callback function addevent:function (type, handler) {//To determine whether an event-handling array has that type of event if (eventtarget.handlers[type] = = undefined
    ) {Eventtarget.handlers[type] = [];
  ///Push the processing event to the event handling array Eventtarget.handlers[type].push (handler); ///Triggers an event//event-> is a JS object with at least the type attribute in the attribute,///Because the type is required, and then some other variable parameters that are required by the handler function can be passed. (This is why we want to pass the JS object) fireevent:function (event) {//To determine if there is a type if (Eventtarget.handlers[event.type] instanceof Array
      ) {var _handler = Eventtarget.handlers[event.type]; There may be multiple processing events under the same event type, finding the event for this need to be handled for (var i = 0; i < _handler.length i++) {//Execute trigger _handler[i] (E
      VENT); }},//Logoff event//type-> custom event type, Handler-> custom event callback function removeevent:function (type, handler) {if (event
      Target.handlers[type] instanceof Array) {var _handler = Eventtarget.handlers[type]; In the same event classThere may be multiple processing events under the type, find out the event for this need to be handled for (var i = 0; i < _handler.length i++) {//Find out the event to be handled the subscript if (_handler[i
        ] = = handler) {break;
    }//Delete processing event _handler.splice (I, 1);
 }
  }
};

This is a way to invoke a run

Eventtarget.addevent ("Eat", function () {
  console.log (123);  123
});
Eventtarget.fireevent ({type: "Eat"});

This approach has a disadvantage that it is not possible to delete the processing event because we do it with the mapping table, and we do not advocate that it is a bit more to save so much data directly into the mapping table.

Another way to extract the processing events (recommended)

Function B () {
   console.log (123);
}
Eventtarget.addevent ("Eat", b);
Eventtarget.fireevent ({
  type: "Eat"
});                   123
eventtarget.removeevent ("Eat", b);
Eventtarget.fireevent ({type: "Eat"});  Empty

You can also pass more arguments.

Eventtarget.fireevent ({
  type: "Eat",
  Food: "Banana"
}); 
function B (data) {
   console.log (data.food);//banana
}

Summary: Literally this method, a bit of a disadvantage, is that in case of carelessness, an attribute in the handler function, assigning null, which will cause our Eventtarget method crash. It seems that prototypes should be a good way to be safer.

3. Object prototype Encapsulation JS custom event

Because the previous ideas are basically clear, here I directly attached code, you can study the pros and cons, perhaps you can find a better way to solve ta ...

Custom Event constructor Function Eventtarget () {//Event handler Array Collection this.handlers = {};}//Custom event prototype Object Eventtarget.prototype = {//Set the original Type constructor chain Constructor:eventtarget,//register event handlers of the given type,//type-> custom event type, Handler-> custom event callback function addevent:function (Type, handler)
    {//Determine if the event handling array has the type event if (typeof this.handlers[type] = = ' undefined ') {this.handlers[type] = [];
  ///Push the processing event to the event handling array This.handlers[type].push (handler); ///Triggers an event//event-> is a JS object with at least the type attribute in the attribute,///Because the type is required, and then some other variable parameters that are required by the handler function can be passed.
    (This is why you want to pass the JS object) fireevent:function (event) {//Simulate the real events event if (!event.target) {event.target = this;
      }//Determine if the event type is present (This.handlers[event.type] instanceof Array) {var handlers = This.handlers[event.type]; There may be multiple processing events under the same event type, identifying the event for which you want to handle (var i = 0; i < handlers.length i++) {//Execute trigger handlers I
      (event); }},//Logoff event//type-> custom event type, Handler-> custom event callback function Removeevent:functioN (type, handler) {//To determine if there is an event type if (This.handlers[type] instanceof Array) {var handlers = This.handlers[type]
      ; There may be multiple processing events for the same event type for (var i = 0; i < handlers.length i++) {//Find the event to be processed subscript if (handlers[i) =
        = handler) {break;
    ///Remove Handlers.splice from the event handling array (I, 1);
 }
  }
};

Call method

Function B () {
  console.log (123);
}

var target = new Eventtarget ();
Target.addevent ("Eat", b);

Target.fireevent ({
  type: "Eat"
});                 123

This method of prototyping is the same as the function of the direct volume method ...

The above is the entire content of this article, I hope to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.