Execute Jquery every time a specific function runs [duplicate]


This question already has an answer here:

<ul><li> <a href="/questions/17202346/do-something-when-function-executes-jquery" dir="ltr" rel="nofollow">do something when function executes Jquery</a> <span class="question-originals-answer-count"> 2 answers </span> </li> </ul>

<strong>Is it possible to execute something every time a specific function runs without any knowledge about that function besides its name?</strong>

This would be similar to bind

var clicked = 0; $('#foo').bind('click',function(){ clicked += 1; alert(clicked); });

So there, every time something with the ID foo is clicked, it will add 1 to the variable clicked so that I know how many times it has been clicked. What I want to do would be the equivalent of the following if it were correct syntax:

var fired = 0; $('my_function').bind('run',function(){ fired += 1; alert(fired); });

I don't care if in any given situation you would be in, you would always be able to figure something out about the function and use that, I don't want work arounds, this is what I want for an answer:

How I can execute something everytime a specific function runs, just given the name of the function. If that is not possible, why not?


Try something like this:

var temp = my_function, fired = 0; my_function = function() { fired++; temp.apply(this,arguments); }


I think something like this may be the closest you can come:

function adjustFunctionToCount(f){ var count = 0; function newF(){ count++; f.apply(this, arguments); } newF.getCount = function(){ return count; }; return newF; }

And so if you have

function handler(val){ console.log('called with val ' + val); }

You could do

handler = adjustFunctionToCount(handler); handler('a'); handler('b'); console.log(handler.getCount());

<a href="http://jsfiddle.net/7sM3L/" rel="nofollow">FIDDLE</a>

And needless to say you could create your function inline

var handler = adjustFunctionToCount(function(val){ console.log('called with val ' + val); }); handler('a'); handler('b'); console.log(handler.getCount());

<a href="http://jsfiddle.net/7sM3L/2/" rel="nofollow">UPDATED FIDDLE</a>


I'm pretty sure that's impossible in the general case.

Remember, functions are objects, really, and the name of a function is just a variable. Functions can exist without being assigned to a named variable, the variables can be out of your scope, or reassigned/swapped around. In any case, I know of no API that lets you hook onto a JS function call.

This may be of interest: <a href="https://stackoverflow.com/questions/3406467/can-i-intercept-a-function-called-directly" rel="nofollow">Can I intercept a function called directly?</a>


This is where event driven programming comes in - and jQuery makes it really easy to do.

var myFunction = function() { //... //... //... $(document).trigger('someEvent'); } $(document).on('someEvent',function() { //the function you would like to run every time myFunction is called });


Try this:

var count = (function(){ var c = 0; return function(){ alert(c++); }; })(); $('#foo').click(count);


$('#foo').bind('click', count);

When an Anonymous Function or a Variable that represents a Function is passed it is the same thing. You could make your own code that executes a Function like this:

function executeFun(func){ return func(); } executeFun(count) executeFun(function(){ /*everything happens in here. The Anonymous Function will be called automatically because of the parameter next to the variable func above */ })

Although, that example is impractical it shows you what happens internally. Also, I solved your potential global scope variable problem with a Closure. For more on Closures visit <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures</a> .


  • How to open a new independent form?
  • Reassigning local commits to a different branch in Mercurial
  • Skip reading strings in MATLAB
  • Count how many strings in an array have duplicates in the same array [duplicate]
  • Select image from gridview and display it on other intent
  • Can not cast IMAPInputStream to Multipart
  • Django Admin. UnicodeEncodeError 'ascii' codec can't encode characters in position 0-
  • How to store items of multiple JSON Array and display it listview?
  • Keeping the user's input intact when outputing to terminal at the same time
  • SCSS Language Injection in Pycharm
  • Configure WAF Application Gateway in front of App Services [closed]
  • Plot a CSV file where the delimiter is '; ' (semicolon + space)
  • Pytest/Allure - How to generate testcase description?
  • Implementing an abstract function with access types in Ada
  • undefined reference error due to use of static variables [duplicate]
  • Time taken for Hadoop job to execute
  • In java, how do you retrieve images from a jar file?
  • Fire callback when selection was made with select2 4.0, and retrieve the value of last selection
  • How to use the resource module to measure the running time of a function?
  • Does the MySQL IN clause execute the subquery multiple times?
  • How dotnet build chooses the output name
  • Lua: Line breaks in strings
  • jQuery - resize an elements height to match window without refreshing, on window resize
  • Perspective projection, 4 points
  • Available space left on drive - WinAPI - Windows CE
  • cell spacing in div table
  • XSLT foreach repeating nodes to flat
  • How to create a 2D image by rotating 1D vector of numbers around its center element?
  • hide missing dates from x-axis ggplot2
  • Thread 1: EXC_BAD_ACCESS (code =1 address = 0x0)
  • Reduction and collapse clauses in OMP have some confusing points
  • GridView breaks while scrolling
  • MongoDb aggregation
  • How to use remove-erase idiom for removing empty vectors in a vector?
  • Django: Count of Group Elements
  • Using jQuery closest() method with class selector
  • Illegal mix of collations for operation for date/time comparison
  • Sending data from AppleScript to FileMaker records
  • MySQL WHERE-condition in procedure ignored
  • WPF Applying a trigger on binding failure