最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - JavaScript decorators HOWTO? - Stack Overflow

programmeradmin1浏览0评论

I need to decorate a 3rd party function that I can't modify so I will need to decorate it in any way. I found that in Prototype there is something to do it easily [1].

Is there any alternative to that in jQuery or in plain JavaScript?

[1] /

I need to decorate a 3rd party function that I can't modify so I will need to decorate it in any way. I found that in Prototype there is something to do it easily [1].

Is there any alternative to that in jQuery or in plain JavaScript?

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

Share edited Mar 15, 2012 at 4:25 reevesy 3,4721 gold badge28 silver badges23 bronze badges asked Dec 4, 2009 at 18:34 Esteban FeldmanEsteban Feldman 3,4076 gold badges33 silver badges31 bronze badges 1
  • NOTE: Need to do it with jquery or plain js, can't add another js framework. – Esteban Feldman Commented Dec 4, 2009 at 18:46
Add a ment  | 

5 Answers 5

Reset to default 4

What about your scenario requires a library? It seems that with native javascript, you could simply:

  • Save a copy of the original function
  • Create a modified version of the function which uses the original
  • Store a reference to the modified version where the original was originally stored.

With jquery, it would be pretty easy to just add in another function to use. Try something like:

//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'); } 
        }
    );
}

Try adding that to your page, and something like this to test it out:

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

Hope this helps you.

I like the wrap functions provided by libraries: Prototype has the wrap function. In ExtJS, one might use createDelegate or createInterceptor. Dojo has declarative AOP. Sans framework, one might do this:

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

You could do it with the jquery AOP plugin: http://code.google./p/jquery-aop/

Code would look like:

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

I will go for Frank Schwieterman solution:

new_func = originalFunc
function myExtendedVersion()
{ 
  // do my stuff
  new_func();
  // do my stuff 
} 
发布评论

评论列表(0)

  1. 暂无评论