Execute Jquery Every Time A Specific Function Runs
Solution 1:
Try something like this:
var temp = my_function, fired = 0;
my_function = function() {
fired++;
temp.apply(this,arguments);
}
Solution 2:
I think something like this may be the closest you can come:
functionadjustFunctionToCount(f){
var count = 0;
functionnewF(){
count++;
f.apply(this, arguments);
}
newF.getCount = function(){ return count; };
return newF;
}
And so if you have
functionhandler(val){
console.log('called with val ' + val);
}
You could do
handler = adjustFunctionToCount(handler);
handler('a');
handler('b');
console.log(handler.getCount());
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());
Solution 3:
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: Can I intercept a function called directly?
Solution 4:
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
});
Solution 5:
Try this:
var count = (function(){
var c = 0;
returnfunction(){
alert(c++);
};
})();
$('#foo').click(count);
OR
$('#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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures .
Post a Comment for "Execute Jquery Every Time A Specific Function Runs"