开发者

Dynamically superseding functions that are not in global scope

I have a script, that based upon specific scenarios, may need to supersede functions to do some processing before eventually calling the original function. (See "'overriding' Javascript Function")

I can get this working in general - here's a basic example using the jQuery plugin Tinyscrollbar (not my intended application, just something quick and easy to illustrate):

(function ($) {
    // Snip..

    function initalize() {
        oSelf.update();
        setEvents();
        return oSelf;
    }

    // Snip..

    function setEvents() {

        (function () {
            var oldInit = wheel;

            wheel = function (oEvent) {
                console.log('Intercept');
                oldInit(oEvent);
            }
        })();

        // Original event code, irrelevant to question
    }

    function wheel(oEvent) {
        // Actual function, related to using the mousewheel
    }

})(jQuery);

When I scroll the mousewheel, the console prints 'Intercept', and the scrollbar moves as originally defined. Wonderful!

However, the function name is hardcoded, and doesn't live in the global scope, so window[] is unavailable (which I like). Is there any possible combination of black magic, 'new Function()', and/or other way to loop through a potential list 开发者_开发知识库of function names (which may change based on other logic) and encapsulate them in this (or similar-in-spirit) manner?

Thanks in advance!


Unfortunately, there's no way to enumerate or dynamically access members in a scope object (with the convenient exception of the global scope/window object)

So you'd need to rephrase your code a bit. Instead of having free-floating functions in your outer function, have objects with methods on them. That'd make replacing those methods much easier.

There's some additional trickiness if you modify your functions after you started assigning them as event handlers or whatever. If you happen to use some kind of bind() wrapper around those functions, the correctness of your behavior will depend a lot on that bind() function.

Specifically, if you want the replacement method to retroactively become the method called for any event handler or callback it was assigned to, you'll want to use a bind() wrapper that takes a context object and a string meant to be the function name rather than a context object and a function reference. (and make sure that bind() doesn't resolve that string early to shave some ms on each calls.)

If don't don't want the retroactive behavior, you still have to make sure you don't have some bind()-ed version of the original method floating around and still being used for new callbacks after your replacement happened.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜