简体   繁体   中英

Javascript bind event handler of another function activating / ending

In Javascript, is there some way to bind and event handler of one function activating and ending?

So, for instance, I have two functions:

function one() { console.log("this is function one") }

and

function two() { console.log("this is function two") }

I want function two to activate both when function one is called and when it ends. Obviously, I could just:

function one() { two(); console.log("this is function one"); two() }

but that'd be boring -- not nearly as interesting as this way.

Well, you could write a function that wraps the original function in another that calls the callback.

function bindStartEnd(originalFn, callback, thisArg) {
    return function() {
        var returnValue;
        callback();
        returnValue = originalFn.apply(thisArg || null, arguments);
        callback();
        return returnValue;
    };
}

It could be used like this:

function one() {
    console.log("This is function one");
}
function two() {
    console.log("This is function two");
}
var three = bindStartEnd(one, two);
three();

And it could be extended to also accept two callbacks, one for the beginning and one for the end. You might also think of a better name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM