JavaScript designers howto?

I need to decorate a third-party function that I cannot change, so I need to decorate it in some way. I found that Prototype has something easy to do [1].

Is there an alternative in jQuery or in plain JavaScript?

[1] http://api.prototypejs.org/language/Function/prototype/wrap/

+5
source share
5 answers

How about your script, a library is required? It seems like with your own javascript you could simply:

  • Save a copy of the original function
  • Create a modified version of the function that uses the original
  • , .
+4

jquery . - :

//Sample function you're wrapping around 
function say_hi(){
    alert('hi');
}

//quick jq plugin
jQuery.fn.functionWrap = function(arg,opts){
    if(opts.before && typeof(opts.before)=='function'){
        opts.before();
    }
    arg();
    if(opts.after && typeof(opts.after)=='function'){
        opts.after();
    }
};


//sample function to use the wrapper func
function btnPress(){
    $().functionWrap(
        say_hi,
        {
            before : function(){ alert('happens before'); }, 
            after : function(){ alert('happens after'); } 
        }
    );
}

- , :

<input type="button" value="asdf" onClick="btnPress();" />

, .

+1

, : Prototype . ExtJS createDelegate createInterceptor. Dojo . Sans, :

myFunction(){
   something();
   thirdParty.call();  // or apply
   perhapsSomethingElse();
}
0

jQuery AOP: http://code.google.com/p/jquery-aop/

:

jQuery.aop.around( {target: window, method: 'originalFunc'}, 
  function(invocation) {
    // do your stuff
    invocation.proceed(); 
    // do your stuff
  }
);
0

:

new_func = originalFunc
function myExtendedVersion()
{ 
  // do my stuff
  new_func();
  // do my stuff 
} 
-1

All Articles