0

I have a function, let call it: myFunction, that I use a lot. Most of the time, I don't care when it's called. However, sometimes, it would be nice to know when it is called so that I can perform certain actions. Is there a way that I can, without editing myFunction, create a listener in jQuery so that when myFunction is done, I can call another function?

for example:

<script>
var foo = "foo";
function myFunction() {
    foo += "bar";
}
function afterMyFunction() {
    alert(foo);
}

$(function() {
    #some sort of listener for when myFunction is done --- ???#

    myFunction();
});
</script>

I would want, when the page loads, for there to be an alert that simply says "foobar". This is obviously a simplified example, but it gets my point across... I hope.

2

1 Answer 1

0

Without editing the function, I don't know how. But with editing you can trigger a custom event like this :

JS

var foo = "foo";
function myFunction() {
    foo += "bar";
    $('body').trigger('myFunctionDone');
}
function afterMyFunction() {
    alert(foo);
}

$(function() {
    $('body').on('myFunctionDone',function(){
        console.log('done');
    });

    myFunction();
});
Sign up to request clarification or add additional context in comments.

1 Comment

I knew about that, i just wasn't sure if there was a way to do what i asked in the original post. Like i said, most of the time, i don't care when the function is called... but on the rare occasions that i do, it'd be nice to be able to add a listener. Thanks for the response!

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.