Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen for a function to be called JavaScript

I have the following functions that is called every 2 seconds to load some data. It registers the funcion [do] to do the stuff with the response. (the example is simplified).

function doRequest (){
    $.ajax({ url: 'www.google.com.pe', success: function (response) {do(response)} });
}

function do (text){
    var i = setInterval(doRequest, 2000);
}

I wonder if there is any way that I can create a function that is called every time the [do] function is called with out needing to add a call to the listener inside the do function. Thank's in advance. If there is any better way to do it with jquery, like a plugin I'd appreciate the help.

[Edit] The idea is not whether it works or not. My question was about if I can add a custom listener to the "do" function wich was allready implemented. Something like addActionListener("do", "after", doSomeThingElse) So I could do some thing else just after the do function has finished.

like image 605
jaxkodex Avatar asked Oct 15 '12 19:10

jaxkodex


1 Answers

First, your simplified version won't work, because you'd need to pass the do function instead of calling it.

function doRequest (){
    $.ajax({ url: 'www.google.com.pe', success: _do });
}

But it sounds like you're asking how to run some other code every time do is invoked.

If do is only invoked inside the doRequest() function, then just add your other code to an anonymous function that invokes do at the right time.

function doRequest (){
    $.ajax({ url: 'www.google.com.pe', success: function(response) {
          // Run your other code
          //   or invoke another function.
          _do(response);
    } });
}

If you want it to be more generalized, you can create a function decorator that returns a function which invokes do after some other code.

function doFactory(fn) {
    return function() {
        fn.apply(this, arguments);
        _do.apply(this, arguments);
    }
}

then make functions like this:

var doFoo = doFactory(function() {
    console.log("foo");
});

If your requirement is more specific of a pre-processing of response, you could rework it like this:

function doFactory(fn) {
    return function(response) {
        _do.call(this, fn.call(this, response));
    }
}

Then have the fn manipulate and return response.

var doFoo = doFactory(function(response) {
    return response + "foo";
});
like image 91
I Hate Lazy Avatar answered Sep 22 '22 14:09

I Hate Lazy