Function listener in javascript and/or jQuery

我的梦境 提交于 2019-12-06 19:19:32

问题


Wondering if there is an elegant way to listen for a function in javascript and/or jQuery.

Rather than listening for a $('#mything').click(function(){ //blah }) I'd like to listen for when a specific function is fired off. I don't want to edit the function as it's within a library that I don't want to hack directly.

I did find this: http://plugins.jquery.com/project/jqConnect which connects functions.

But wondering about a better technique.


回答1:


The only way to do this is to override the function (ie, hack the library):

(function() {
    var oldVersion = someLibrary.someFunction;
    someLibrary.someFunction = function() {
        // do some stuff
        var result = oldVersion.apply(this, arguments);
        // do some more stuff
        return result;
    };
})();

Edit: To run your code after the library function has run, just call the library function first, storing the result in a variable. Then, run your code, and finally return the previously stored result. I've updated my example above to accomodate running code either before or after the library function.



来源:https://stackoverflow.com/questions/8073403/function-listener-in-javascript-and-or-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!