Adding Code to a JavaScript Function Programmatically

Adding code to a javascript function programmatically

If someFunction is globally available, then you can cache the function, create your own, and have yours call it.

So if this is the original...

someFunction = function() {
alert("done");
}

You'd do this...

someFunction = (function() {
var cached_function = someFunction;

return function() {
// your code

var result = cached_function.apply(this, arguments); // use .apply() to call it

// more of your code

return result;
};
})();

Here's the fiddle


Notice that I use .apply to call the cached function. This lets me retain the expected value of this, and pass whatever arguments were passed in as individual arguments irrespective of how many there were.

Append code to the end of an existing function

You can just override foo with a custom function that calls the original.

E.g.

var old_foo = foo;
foo = function() {
old_foo();
bar();
}

You should also pass any arguments foo takes into it via your replacement function.

Is it possible to add some code to existing javascript functions without modify original code?

You can't modify functions, but you can wrap them and replace the function with the wrapper.

Such (see a live demo):

function logFactory(func, message) {
return function () {
console.log(message);
return func.apply(this, arguments);
}
}

hello = logFactory(hello, "Some log message");

This won't let you get any data while it is being manipulated by the function though or change what happens inside the function (although you can capture the arguments and modify them before passing them on, and you can capture the return value and modify it before returning it).

Add code to a function in angular programmatically

You can use jQuery to find the scope and the function and modify it:

var $scope = $('[ng-click="paginationApi.nextPage()"]').scope();
var original_function = $scope.paginationApi.nextPage;
$scope.paginationApi.nextPage = function() {
// do some stuff
original_function.apply(this, arguments);
};

Calling JavaScript Function From CodeBehind

You may try this :

Page.ClientScript.RegisterStartupScript(this.GetType(),"CallMyFunction","MyFunction()",true);

How to automatically handle javascript function call and wrap/decorate it

Finally I decided to use described at this link technique:

Adding code to a javascript function programmatically

I set up at document ready to search function clearData()

$( document ).ready(function() {
decorateClearData();
});

and code in function decorateClearData();

function decorateClearData() {
clearData = (function() {
var cached_function = someFunction;

return function() {
cached_function.apply(this, arguments); // use .apply() to call it

// and my new code:
removeItemFromTable();
};
}());
}

This works because clearData is global function, and maybe this is not pragmatic way but I didn't have other ideas.



Related Topics



Leave a reply



Submit