0

In javscript we can do this

var text = "the original text";

text+=";Add this on";

If a library has a function already defined (e.g)

//In the js library
library.somefunction = function() {...};

Is there a way to add something on so that I can have two functions run?

var myfunction = function() {...};

Something like:

library.somefunction += myfunction

So that both myfunction() and the original library.somefunction() are both run?

3
  • 1
    Do you want the library's function to be changed to run both the original function and your custom function or do you want a new function that runs both? Commented May 7, 2013 at 8:19
  • I want the library's original function changed to run both Commented May 7, 2013 at 8:29
  • Could you check the difference jsfiddle.net/TLStb Commented May 7, 2013 at 9:29

2 Answers 2

1

You can use this kind of code (leave scope empty to use default scope):

var createSequence = function(originalFn, newFn, scope) {
    if (!newFn) {
        return originalFn;
    }
    else {
        return function() {
            var result = originalFn.apply(scope || this, arguments);
            newFn.apply(scope || this, arguments);
            return result;
        };
    }
}

Then:

var sequence = createSequence(library.somefunction, myFunction);
Sign up to request clarification or add additional context in comments.

1 Comment

Hi rab, I checked it and it was not passing the scope at originalFn.apply. Fixed that now
0

I think what you want to create is a Hook (function) - you want to call library.somefunction but add a bit of your own code to run before. If that's the case, you can make your myfunction either call or return the library function after it's done with your bit of code.

var myfunction = function() {

    // your code
    // ...

    return library.somefunction();
}

1 Comment

I also need to ensure that myfunction() is hooked in when library.somefunction() is called

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.