Listen to a function called JavaScript

I have the following functions that are called every 2 seconds to load some data. It registers funcion [do] to make the material respond. (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 a way to create a function that is called every time the [do] function is called with the need to add a call to the listener inside the do function. Thanks in advance. If there is a better way to do this with jquery, like a plugin, I would appreciate help.

[Edit] The idea is not whether it works or not. My question was whether it was possible to add a custom listener to the do function, which was fully implemented. Something like addActionListener ("do", "after", doSomeThingElse) So I could do something else after the do function completes.

+7
source share
3 answers

If you want to keep the existing code as is, you can transfer do() to another function, which in turn calls do() and your new function (say do_this_as_well() ).

See the example below (I renamed do() to do_this() to avoid confusion around the reserved do keyword). This works because global functions are nothing more than variables with function objects in them. These variables can be overwritten, in this case with a new function that calls the old one:

 function do_this(response) { ... } (function() { var previous=do_this; do_this=function(response) { previous(response); do_this_as_well(); } })(); 
+5
source

First, your simplified version will not work, because you need to pass the do function instead of calling it.

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

But it looks like you are asking how to run some other code every time you call do .

If do is only called inside the doRequest() function, just add your other code to the anonymous function, which calls 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 that calls do after some other code.

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

then perform the following functions:

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

If your requirement is more specific to preprocessing a response , you can redo it as follows:

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

Then do fn manipulate and return a response .

 var doFoo = doFactory(function(response) { return response + "foo"; }); 
+6
source

Replace

 success: do(response) 

from

 success: function(response) { do(response); do_this_as_well(); } 
+1
source

All Articles