JavaScript removes anonymous event handlers that are bound to elements

Source: Internet
Author: User

Objective:

It was a bit of a job interview, and after that, it seemed like you misunderstood the interviewer's question, because the question I understood was meaningless. But there were some ideas, but stuck at one point.

After the end of the brain a moment of light, came up with the small step that was not taken. So do not care about the meaning of the question itself, simply want to put this I understand the wrong problem to solve, it is to meet their own a small wish.

Problem:

When you bind an event handler to a DOM element with AddEventListener () and attachevent (), if an anonymous function is passed in, then the corresponding RemoveEventListener () and DetachEvent () It is not possible to unbind this anonymous handler. So we should pass in a function expression when we use it.

So, what if I just want to use anonymous functions to bind and unbind?

Ideas:

Since both functions are so cold that they do not accept the same anonymous function to be unbound, it is only possible to find another way to manage the event.

So you need a custom object to manage the events.

The essence of an event handler is that when an event occurs on an object, the function that listens to the event is executed.

Translation:

A DOM element may be bound to a handler for more than one event type. For example, when the click Color Changes, mouseover when the time becomes larger.

An event type may bind multiple event handlers. For example, when mouseover and change color and become larger.

Therefore, this event object should have a property to store all the event handlers that are bound by this DOM element, and there should be two methods, one to add, and one to delete.

{Handlers:{type1:[handler1,handler2],type2:[handler1,handler2],...//other event type and corresponding event handler function},on:function () {},off: function () {}}

When an event occurs, all functions within the array of the corresponding event type in this object are called.

So the binding event is to add a function to the corresponding array, and the Unbind event is to delete the function from the array.

So how do you ensure that the correct DOM element is being manipulated?

Obviously, each DOM element should need one such object to manage its own event handlers.

Every object has something, that's not his attribute. (And I was stuck here).

Realize:

Each DOM element requires such an object, and the On () and Off () methods in each object are the same, so a constructor is needed to put the two methods into his prototype object.

function Eventmanage () {  this.handlers={}}eventmanage.prototype={  on:function (type,handler) {    if (! This.handlers[type]) {      This.handlers[type]=[handler];      return True ;  Avoid adding multiple events    }else{      This.handlers[type].push (handler);    }  ,  off:function (Type,handler) { For    (Var i=0,len=this.handlers[type].length;i<len;i++) {      if (this.handlers[type][i].tostring () = = Handler.tostring ()) {        this.handlers[type].splice (i,1);}}}  

Each object has these two methods to add and remove event handlers on its own, but to listen for events or to rely on JavaScript-provided methods, borrowing Addeventlistner () and attachevent () to listen for events:

var eventutil={}; Eventutil.on=function (ele,type,handler) {  if (!ele.event) {    ele.event=new eventmanage ();  }  var isnewtype=ele.event.on (Type,handler);  var fire=function () {for      (var i=0,len=ele.event.handlers[type].length;i<len;i++) {        ele.event.handlers[ Type][i] ();      }    ;  if (Isnewtype) {    if (ele.addeventlistener) {      ele.addeventlistener (type,fire,false);    } else{      ele.attachevent ("on" +type,fire);}}  Eventutil.off=function (ele,type,handler) {  ele.event.off (type,handler);}

One thing to note here is that each time you use Eventutil.on (), a fire function is redefined, and AddEventListener () adds multiple identical event handlers to the same event type, so you need to decide if the event type is new, If yes, then use AddEventListener () to listen for this event type.

Examples of Use:
var Btn=document.getelementbyid ("btn"); Eventutil.on (BTN, "click", Function () {  console.log ("11");}); Eventutil.on (BTN, "click", Function () {  console.log ("22");}); Eventutil.off (BTN, "click", Function () {  console.log ("11");});

When you click Btn, only "22" is printed, indicating that the anonymous function was successfully unbound.

JavaScript removes anonymous event handlers that are bound to elements

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.