How to dynamically change the contents of a function using JavaScript - javascript

To help understand this the function is in the html page and it is generated, I cannot change the generated code:
function Update_qu7260() {
var newVal = ''
for( var idx = 0; idx < 2; idx++ )
{
var test
if( idx == 0 ) test = text7263
else if( idx == 1 ) test = text7265
if( test.matchObj ) newVal += test.leftSel + "-" + test.matchObj.rightSel + ","
}
newVal = newVal.substring( 0, newVal.length-1 )
VarQuestion_0001.set( newVal )
qu7260.hasBeenProcessed=false;
doImmFeedback('qu7260');
}
var qu7260 = new Object();
...
qu7260.updFunc = Update_qu7260;
var qObj=[qu7260];
Note in the above the number "7260", the numbers start at 1 so there are lots of them and each Update_###() will be different so I cannot re-write them with "hard wired" code. My code is in an external JavaScript file and is executed onLoad:
...
var updFunc = qObj[0].updFunc.toString();
if(updFunc.indexOf('doImmFeedback(')!=-1){
updFunc = updFunc.replace('doImmFeedback','doImmQuestionFeedback'); // do my function
updFunc = updFunc.replace('function ',''); // remove the word function
var funcName = updFunc.substr(0,updFunc.indexOf('(')); // get the function name e.g. Update_qu7260
updFunc = "window['" + funcName + "']=function" + updFunc.replace(funcName,'');
eval(updFunc);
}
...
When I change the eval() to alert() I can see the that it's correct, however, the eval() is not raising any errors and my function doImmQuestionFeedback is not being called. When I subsequently do an alert(qObj[0].updFunc.toString()) I see the original function.
It would seem that I have provided information that is too complex, so the following code is a better example:
function hi(){alert('hi');}
function changeHi(){
hi(); // I get an alert box with hi
newHi = "function hi(){alert('hi there');}"
eval(newHi);
hi(); // I get an alert box with hi
window.setTimeout('hi()',500); // I get an alert box with hi
}
window.setTimeout('changeHi()',500);
The following is the original question:
I have a predefined function that I did not create, however, I know it's name so I can get the function itself and then I change it by doing:
var funcText = window.updateFunc.toString();
funcText = funcText.replace('doSomeOtherFunction(','doMyFunction(');
How do I update the actual function so it will do all that it did before except it will now call doMyFuntion()?
The following is an example to help visualize what I want to do, the actual function I need to change is very complex. I have:
function updateFunc(whatToUpdate,true){
... - do lots of stuff.
var retVal = doSomeOtherFunction(whatToUdate);
... - do lots of stuff based on retVal
}
I need to change this to:
function updateFunc(whatToUpdate,true){
... - do lots of stuff
var retVal = doMyFunction(whatToUdate);
... - do lots of stuff based on retVal, I have had a chance to change retVal
}
Then the first thing my function will do is call doSomeOtherFunction() check/change the returned value and subsequently return the value to the updateFunc().
I have tried to manipulate the funcText above to:
funcText = 'window.updateFunc = function(...';
eval(funcText);
Without success.

This may be closed enough to what you are looking for.
Assuming you have this original function:
function originalFunc(val) {
// this function converts input string to upper case
return val.toUpperCase();
}
Now you want to override it to something either before or after you execute that function (in this example, we execute before, of course before or after doesn't matter in this case).
// we preserve orignal function
var originalFunc_save = originalFunc;
// now we override the original function with this block
var originalFunc = function(text) {
// lets call the orignal function
text = originalFunc_save(text);
// now do our custom thing
return text.split('').reverse().join('');
}
So our test should work.
var text = 'This is a test';
console.log(originalFunc(text));
Output:
TSET A SI SIHT
This method also works if you have to override functions inside a class. The only thing we have to be careful of is to choose a saved name that doesn't interfere with the original class code. _save may not be good enough, but you get the idea.
UPDATE: I'm updating this code above to use a string variable pointing to the original function. I think this is what the OP wanted.
Original code which defined by some library
function originalFunc(val) {
// this function converts input string to upper case
return val.toUpperCase();
}
Now we use the func string variable to point to that function and execute it.
var text = 'This is a test';
var func = 'originalFunc';
text = window[func](text);
console.log(text);
Output: Of course we get the original intended result because we haven't overridden it.
THIS IS A TEST
Now we write our code to override the original function behavior using a string pointing to the function.
// let's define a new function string
var funcSaved = func + '___saved';
// now preserve the original function code
window[funcSaved] = window[func];
// override the original function code block
window[func] = function(text) {
// lets call the orignal function
text = window[funcSaved](text);
// now do our custom thing
return text.split('').reverse().join('');
}
// let's test the code
text = 'This is a test';
text = window[func](text);
console.log(text);
Output:
TSET A SI SIHT

You can make a clone of updateFunc function, edit it at your discretion and work with it in what follows.
function updateFunc(whatToUpdate, param){ // the initial function
...
var retVal = doSomeOtherFunction(whatToUpdate);
return retVal;
}
// formation of unnamed function as string
var newfunc = updateFunc.toString().replace('function updateFunc', 'function ').replace('doSomeOtherFunction(', 'doMyFunction(');
function doMyFunction(whatToUpdate){ // your new function, just for example
console.log(parseInt(whatToUpdate) * 10);
}
var newUpdateFunc;
// declaring new version of 'updateFunc' function
// which is stored in 'newUpdateFunc' variable
eval("newUpdateFunc = " + newfunc);
newUpdateFunc(3); // outputs '30'

I believe this is a valid use case for the forgotten JavaScript with feature.
Basic idea: you call original updateFunc supplying your own version of doSomeOtherFunction to it using with namespace injection:
function updateFunc(whatToUpdate,true){
... - do lots of stuff.
var retVal = doSomeOtherFunction(whatToUdate);
... - do lots of stuff based on retVal
}
function patchUpdateFunc() {
var original_doSomeOtherFunction = window.doSomeOtherFunction;
var original_updateFunc = window.updateFunc;
function doMyFunction() {
// call original_doSomeOtherFunction() here,
// do your own stuff here.
};
window.updateFunc = function() {
with ({doSomeOtherFunction: doMyFunction}) {
return original_updateFunc.apply(this, arguments);
}
}
}
patchUpdateFunc();

I think you are going at this way too complicated.
If you only have doMyFunction and doSomeOtherFunction to switch between, you could just create a flag somewhere telling you to use one or the other when used in an if-statement.
If you want to call a function with a name you do not know beforehand and you only get a name during runtime, you could either accept the function to call as a parameter or accept the name of the function as a parameter and call it like so: var retVal = window[functionName](); (assuming functionName is a property of the window object).
I would highly recommend directly accepting a function as a parameter since the function may not be defined in a global scope.
EDIT:
After your clarification, I think, I can give you a satisfying answer:
if you have a string like var functionString = "function updateFunc(whatToUpdate){var retVal = doMyFunction(whatToUpdate);}";
You can define a function using a Function object:
window.updateFunc = new Function("whatToUpdate", "return (" + functionString + ")(whatToUpdate)");
This will replace the already existing function and you can give it any valid function string you want as long as you know and specify the arguments.

If I understood correctly, you want to override the external function. You can achieve that with the following code
//Someone else's function
function externalFunction(foo){
return "some text";
}
//Your function
function myFunction(value){
//Do something
}
//Override
var externalFunction = (function(){
var original = externalFunction; //Save original function
return function(){
var externalFunctionReturnValue = original.apply(this, arguments);
return myFunction(externalFunctionReturnValue);
}
})();
I strongly sugest not to use eval, but since you want to parse javascript from string:
function hi(){alert('hi');}
function changedHi(){
hi(); // I get an alert box with hi
newHi = "window['hi'] = function(){alert('hi there');}"
eval(newHi);
hi(); // I get an alert box with hi there
window.setTimeout('hi()',500); // I get an alert box with hi there
}
window.setTimeout('changedHi()',500);
UPDATE:
This code snippet works which is your original code:
<script type="text/javascript">
function doImmFeedback(foo){
console.log("DoImmFeedback: " + foo);
}
function Update_qu7260() {
console.log("Some code")
doImmFeedback('qu7260');
}
</script>
<script type="text/javascript">
var qu7260 = new Object();
qu7260.updFunc = Update_qu7260;
var qObj=[qu7260];
var updFunc = qObj[0].updFunc.toString();
if(updFunc.indexOf('doImmFeedback(')!=-1){
updFunc = updFunc.replace('doImmFeedback','doImmQuestionFeedback'); // do my function
updFunc = updFunc.replace('function ',''); // remove the word function
var funcName = updFunc.substr(0,updFunc.indexOf('(')); // get the function name e.g. Update_qu7260
updFunc = "window['" + funcName + "']=function" + updFunc.replace(funcName,'');
console.log(updFunc);
eval(updFunc);
}
function doImmQuestionFeedback(foo){
//Your function
console.log("doImmQuestionFeedback: " + foo);
}
Update_qu7260(); //This executes your doImmQuestionFeedback
</script>
So if your function isn't running, your function isn't in the global scope, or something else is happening, and we can't know if don't have any more info. Check your developer's console for javascript errors.

Related

addEventListener not working in Javascript but jQuery Click is working

I am using modular pattern of javascript and trying to do things in Javascript way rather than Jquery
myapp.module1 = (function($){
"use strict";
var _config = {
backgroundImages : document.getElementsByClassName('img_paste'),
}
for(var i = 0;i < _config.backgroundImages.length; i++){
var imageElement = _config.backgroundImages[i];
imageElement.addEventListener('click',myapp.module2.addBackgroundImage(imageElement),false);
}
// $('.img_paste').click(function(){
// var img = this;
// console.log(this);
// console.log($(this));
// myapp.module2.addBackgroundImage(img);
// });
})(jQuery);
In the above code, the Jquery click function works but not the Javacript one.
When I tried to debug, I tried to console out the image in addBackgroundImage() function.
var addBackgroundImage = function(imageToBeAdded){
console.log(imageToBeAdded);//
_addImageToCanvas(imageToBeAdded);
}
The function seems to be executing even before onclick. Why is that happening?
First, the images elements appear to be empty in the console, then after some some the image elements are displayed in console.
Take a look at this simple code example:
function describeTheParameter(p) {
console.log("describeTheParameter invoked. p is of type " + typeof(p));
}
function stringFunction() {
return "Hello World!";
}
describeTheParameter(stringFunction());
describeTheParameter(stringFunction);
This results in
describeTheParameter invoked. p is of type string
describeTheParameter invoked. p is of type function
In the first call, we are calling stringFunction, and then passing the result to describeTheParameter.
In the second call, we are actually passing the function to describeTheParameter.
When you call addEventListener you must follow the pattern of the second call: pass the function without invoking it:
In the following line of code, you are invoking addBackgroundImage, and then passing the result (which will be undefined) to addEventListener.
imageElement.addEventListener('click',myapp.module2.addBackgroundImage(imageElement),false);
You need to pass a yet-to-be-called function into addEventListener.
The smallest step to make your code work is to employ a currying function:
function addImage(imageElement) {
return function() {
myapp.module2.addBackgroundImage(imageElement);
}
}
for(var i = 0;i < _config.backgroundImages.length; i++){
var imageElement = _config.backgroundImages[i];
imageElement.addEventListener('click', addImage(imageElement), false);
}
For much simpler code, make use of the this keyword. In this case, this will point to the element that's firing the event.
function imageClickHandler() {
var imageElement = this;
myapp.module2.addBackgroundImage(imageElement);
}
for(var i = 0;i < _config.backgroundImages.length; i++){
var imageElement = _config.backgroundImages[i];
imageElement.addEventListener('click', imageClickHandler, false);
}
The function seems to be executing even before onclick. Why is that happening?
Look at the statement you wrote:
myapp.module2.addBackgroundImage(imageElement)
You are calling the function and then passing its return value as the function argument.
You want something more along the lines of:
myapp.module2.addBackgroundImage.bind(myapp.module2, imageElement)
(or the function expression that you used in the commented out code)

How to define value of variable from one function to another?

Hello i have this function for example:
var dt = new Date();
var now = dt.valueOf();
function date1() {
var d1 = Math.ceil(
(Math.abs(now - dt.setUTCFullYear(2005))) / (1000*3600*24*365)
);
}
And i want to get value from d1 var to another function for example:
function res() {
document.write(d1).value;
}
Make your function return the value:
var dt = new Date();
var now = dt.valueOf();
function date1() {
return Math.ceil( // <=== Change, using return rather than setting a variable
(Math.abs(now - dt.setUTCFullYear(2005))) / (1000*3600*24*365)
);
}
Then call the function when you need the value:
function res() {
document.write(date1()).value;
// Change -----^^^^^^^
}
Side note: As far as I'm aware, document.write doesn't have any return value, so the .value on the end of your document.write line doesn't make any sense, and will probably result in a TypeError complaining that you're trying to access a property on undefined.
Side note 2: In general, document.write isn't a great way to put information on web pages, use the DOM instead. Like most rules, there are exceptions.
If you want to access the local variables of function A from function B you have to put the definition of function B somewhere inside of the body of function A.
function A() {
var variable;
function B() {
// can access variable here
}
}

why value is not changing of a `var` when it is in the scope of the function

just look at this question: What is the scope of variables in JavaScript?
in the answer which is accepted look at the point 3
according to him a will be 4 but now look at my function:
function JIO_compiler(bpo){ // bpo means that " behave property object " and from here i will now start saying behave property to behave object
var bobj = bpo, // bobj = behave object
bobj_keys = Object.keys(bobj), // bobj_keys = behave object keys. This willl return an array
Jcc_keys = Object.keys(JIO_compiler_components), // Jcc = JIO compiler components
function_code = ""; // get every thing written on every index
if (bobj.hasOwnProperty('target') === false) { // see if there is no target defined
console.log("No target is found"); // tell if there is no target property
throw("there is no target set on which JIO-ASC will act"); // throw an error
};
if (bobj.hasOwnProperty('target') === true) {
console.log("target has been set on "+ bobj['target']+" element"); //tell if the JIO-ASC has got target
function x(){
var target_ = document.getElementById(bobj['target']);
if (target_ === null) {throw('defined target should be ID of some element');};
function_code = "var target="+target_+";";
console.log("target has successfully been translated to javascript");//tell if done
};
};
for(var i = 0; i < bobj_keys.length; i++){
if(bobj_keys[i] === "$alert"){ // find if there is $alert on any index
var strToDisplay = bobj[bobj_keys[i]];
var _alert = JIO_compiler_components.$alert(strToDisplay);
function_code = function_code+ _alert;
};
};// end of main for loop
alert(function_code);
new Function(function_code)();
};
well it is big... but my problem is in the second if statement. now according to the accepted answer the value of function_code should change according to what is instructed. but when at last i alert the function code then it alert blank. i mean it should alert at least var target = something ; and the last console.log statement of this if statement is not showing text in the console.
so what is wrong in this ?
You're setting function_code inside the definition for function x(), but x() is never called. function_call won't change until you make a call to x.
thats because your variable is inside the function scope, you need to define your variable outside of it, as
function_code = "";
function JIO_compiler(bpo){
....
};// end of main for loop
//call the function
JIO_compiler(some_parameter);
//alert the variable
alert(function_code);
you need to call the function JIO_compiler() first so that the appropriate value is set to function_code variable from JIO_compiler() function, as

calling a javascript function from a string passed to the function

i have seen multiple questions of a similar nature on here, yet none would work for the specific thing that i have (im using node.js). so for example take this code here.
function command_call(message, socket) {
if (message.length > 1){
var func = message[0];
var string = message.slice(1);
var string = string.join(' ')}
else{
var func = message[0];
var string = '';};
if(func[0] == '$') {
(eval(func.slice(1)))(string, socket);};
};
function say(string, socket){
socket.write(string)};
if the message passed in to the command_call were to be "$say hi" the function say would be called and return "hi". this works just fine however, if the function that was put to the eval does not exist, it crashes. for instance if the message passed to the command_call were to be "$example blah" it would try to eval "example". basically i need it to check if the function exists before it evals the function. and YES i want to use eval, unless there is a better way to do it in node. and again, this is in node.js
You should make an object of functions and use indexer notation:
var methods = {
$say: function() { ... }
};
if (!methods.hasOwnProperty(func))
// uh oh
else
methods[func]();

How to reference a variable dynamically in javascript

I am trying to reference a variable dynamically in javascript
The variable I am trying to call is amtgc1# (where # varies from 1-7)
I am using a while statement to loop through, and the value of the counting variable in my while statement corresponds with the last digit of the variable I am trying to call.
For Example:
var inc=3;
var step=0;
while(step < inc){
var dataString = dataString + amtgc1#;
var step = step+1;
}
Where # is based on the value of the variable "step". How do I go about doing this? Any help is appreciated! Thanks!!
Rather than defining amtgc1[1-7] as 7 different variables, instantiate them as an array instead. So your server code would emit:
var amtgc1 = [<what used to be amtgc11>,<what used to be amtgc12>, ...insert the rest here...];
Then, you can refer to them in your loop using array syntax:
var dataString = dataString + amtgc1[step];
The only way you can do this (afaik) is to throw all of your amtgc1# vars in an object such as:
myVars = {
amtgc1: 1234,
amtgc2: 12345,
amtgc3: 123456,
amtgc4: 1234567
};
Then you can reference it like
myVars["amtgc" + step];
How about:
var dataString = dataString + eval('amtgc1' + step);
It is true that eval() is not always recommended, but that would work. Otherwise depending on the scope, you can reference most things like an object in JavaScript. That said, here are examples of what you can do.
Global scope
var MyGlobalVar = 'secret message';
var dynamicVarName = 'MyGlobalVar';
console.log(window.[dynamicVarName]);
Function Scope
function x() {
this.df = 'secret';
console.log(this['df']);
}
x();
Not tested, but can't see why you can't do this...
$('#amtgc1' + step).whatever();
If your amtgc1* variables are defined as a property of an object, you can reference them by name. Assuming they are declared in the global scope, they will be members of the window object.
var inc=7;
var step=0;
while(step < inc){
var dataString = dataString + window['amtgc1'+(step+1)];
var step = step+1;
}
If they are defined in a different scope (within a function) but not belonging to any other object, you're stuck with eval, which is generally considered bad.
also, hooray for loops!
var inc=7;
for ( var step=0; step < inc; step++ ){
var dataString = dataString + window['amtgc1'+(step+1)];
}
I have built a way which you could solve this problem using objects to store the key values, where the key would be the reference to the task and the value will be the action (function) and you could use an if inside the loop to check the current task and trigger actions.
If you would like to compare dynamically concatenating strings with "variable", you should use the eval() function.
/* store all tasks references in a key value, where key will be
* the task reference and value will be action that the task will
* Execute
*/
var storeAllTasksRefer = {
amtgc11:function(){ alert("executing task amtgc11"); },
amtgc112:function(){ alert("executing task amtgc112"); },
"amtgc1123":"amtgc1123"
// add more tasks here...
};
var inc = 7;
var step = 1;
var dataString = 'amtgc1';
while(step <= inc){
var dataString = dataString + step;
//alert(dataString); // check its name;
step = step+1;
// check if it is my var
if( dataString == 'amtgc112' ){
// here I will reference my task
storeAllTasksRefer.amtgc112();
}// end if
/* you can also compare dynamically using the eval() function */
if('amtgc1123' == eval('storeAllTasksRefer.'+dataString)){
alert("This is my task: "+ eval('storeAllTasksRefer.'+dataString));
} // end this if
} // end while
Here is the live example: http://jsfiddle.net/danhdds/e757v8ph/
eval() function reference: http://www.w3schools.com/jsref/jsref_eval.asp

Categories

Resources