[removed] Adding an onClick handler without overwriting the existing one

前端 未结 7 1179
说谎
说谎 2020-12-14 02:54

I\'m trying to modify all links on a page so they perform some additional work when they are clicked.

A trivial approach might be something like this:



        
7条回答
  •  粉色の甜心
    2020-12-14 03:41

    Use a wrapper around addEventListener (DOM supporting browsers) or attachEvent (IE).

    Note that if you ever want to store a value in a variable without overwriting the old value, you can use closures.

    function chain(oldFunc, newFunc) {
      if (oldFunc) {
        return function() {
          oldFunc.call(this, arguments);
          newFunc.call(this, arguments);
        }
      } else {
        return newFunc;
      }
    }
    
    obj.method = chain(obj.method, newMethod);
    

    In Aspect Oriented Programming, this is known as "advice".

提交回复
热议问题