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
ES5
can be implemented by adding a wrapper function:
_windowonload = window.onload;window.onload = function(){ additionalListener(); if (someCondition){ _windowonload(); }}
Three. ES6 method
ES6
The 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