Talk About it today | How to add listeners without affecting the monitoring of existing events in JS

Source: Internet
Author: User

I. Clarification of needs

For example, a button has been bound to 2-3 of the Window object of the listener load , now need to add a new listener to the click event, but under certain conditions will trigger the original 2-3 load listeners, otherwise only trigger the newly added event.

Assume that the newly added listener function is:

function additionalListener(){    console.log(‘should do something else‘);}
Two. ES5 method

ES5can be implemented by adding a wrapper function:

_windowonload = window.onload;window.onload = function(){    additionalListener();    if (someCondition){        _windowonload();    }}
Three. ES6 method

ES6The proxy object added Proxy can also be used to implement this requirement, the basic logic is to implement the window.onload call hijacking:

 var onloadProxy = new Proxy(window.onload,{    apply:function () {        additionalListener();        Reflect.apply(...arguments);    }  });  window.onload = onloadProxy;
Four. AOP methods

AOP, that is, aspect-oriented programming, from the perspective of meta-programming to achieve chained calls (it is recommended that the general programmer do not add new features on the original object), the implementation of the logic is to add a method on the prototype object of the function, after it receives a function as a parameter, when the function is called first call the original function, and then call after method, and finally returns the result of the original function's execution:

  Function.prototype.after = function (afterFn) {      return () => {         const result = this.apply(this, arguments);          afterFn.apply(this,arguments);          return result;      }  }  window.onload = window.onload.after(additionalListener);

Talk About it today | How to add listeners without affecting the monitoring of existing events in JS

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.