Let's say I have an object with this markup:
var obj = {
cat: function(string, bool, NEEDTHIS) {
console.log(string, bool, NEEDTHIS);
}
}
Lets say I have the function, with it's variables as an attribute on a button which I have NO control over how it's generated. Example:
<button type="button" onclick="obj.cat('foo', true, 'dog');">PRINT</button>
I need to run this function on the button, but remove the attribute so that I can parse my own attribute.
So I'd strip the attribute 'onclick', store it in a string like so:
var function = "obj.cat('foo', true);";
surely there's a way to just add in another argument without literally altering the string.
I'm also stuck on how I could run the function as it is from the string.
is this possible?
use eval
var function = "obj.cat('foo', true);";
eval(function);
Related
I would like to produce a Javascript object which contains a property (onClick example) of type function (myClickHandler example) like this:
var options = {onClick: this.myClickHandler};
I want the object above to be created from a string because the options object can be different every time the app runs and I want it to be evaluated during runtime. (myClickHandler is an existing function). I want the options object created from a string because onClick property can be something else and its function can be something else also. These are determined from the string which is dynamic.
Looking for something like this:
var optionsString = "{onClick: this.myClickHandler}";
var options = JSON.parse(optionsString); //won't work. For illustration only.
This won't work naturally. Ideally, I want to convert the string in one go but I might have to parse it but optionString can contain one or more properties.
Try using eval as :
var myClickHandler = function(){ alert('i am evil'); };
var options = JSON.parse('{ "onClick": "this.myClickHandler" }');
// calling handler now
eval(options.onClick)();
You need some context where the function is bound to, so that you can access the function by key (which can be a string).
let context = {};
context.myclickhandler = () => {
console.log("### It clix ####")
}
let nameOfFunction = "myclickhandler"
let obj = {"onClick" : context[nameOfFunction]};
obj["onClick"]();
In the example the context is just an object , but it could also be the windows object or a instance of a constructor function.
I'm generating a JavaScript object in a Java class for use in javascript the result looks like this:
var gridDefinition = {"width":"100%",
"height":700,
"sortable":true,
"columns"[{"datafield":"id","datatype":"string","width":300,"hidden":true,"text":"ID"},
{"datafield":"lastname","datatype":"string","cellsrenderer":"renderer_openEntry","width":300,"text":"Nachname"},
{"datafield":"firstname","datatype":"string","width":200,"text":"Vorname"},
{"datafield":"officePhoneNumber","datatype":"string","width":150,"text":"Telefon"},
{"datafield":"companyName","datatype":"string","width":300,"text":"Firma"},
{"datafield":"mailServer","datatype":"string","width":200,"text":"Mail-Server"},
{"datafield":"mailFile","datatype":"string","width":400,"text":"Mail-Datei"}]} ;
cellsrenderer is a callback function name. How can I remove the doublequotes surrounding renderer_link? The result line should look like this:
{"datafield":"lastname","datatype":"string","cellsrenderer":renderer_openEntry,"width":300,"text":"Nachname"},
How to "remove the quotes" is the wrong question to ask. At the moment the code is running, there are no quotes that can be removed.
What you need is a map that maps a name to a variable, e.g.
var myFunctions = {
renderer_openEntry: renderer_openEntry,
// other functions
};
and then process the object to update the values of all cellsrender proeprties to refer to the value from the map instead of the string:
gridDefinition.columns.forEachfunction(column) {
if (column.cellsrenderer) {
column.cellsrenderer = myFunctions[column.cellsrenderer];
}
});
I have created a function named “show_alphabet” and assign to a variable named “str”, a string of the letters of the alphabet in uppercase.
I have used the prototype property of the String object to add a method named “sendArray” and assign this (sendArray) a function which returns the split() method. The split() method will split the alphabet string.
I also have a variable named “arr” and I have assigned it the sendArray() method for “str”.
I have a button that when clicked will run the show_alphabet function.
The function is supposed to display the alphabet letters in the “str” as an array with period colon followed by each letter and placing each letter on a separate line.
For example:
A:
B:
C:
…
However, whenever I click on the button, nothing is displayed.
Here is my code:
<form>
<button type = "submit" value = "submit" onclick = "show_alphabet()">submit </button>
</form>
<script type="text/javascript">
function show_alphabet() {
var str = new String("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
String.prototype.sendArray() = function() {
return this.split("");
}
for (i=0; i<str.length-1; i++) {
var arr = str.sendArray(":" + "<br />");
document.write(arr[i]);
}
}
</script>
I couldn't stand these horrible answers, so I felt compelled to offer a correct one.
<button type="button" value="submit" onclick="show_alphabet()">submit</button>
<div id="dynamic"></div>
<script type="text/javascript">
function show_alphabet() {
var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.querySelector('#dynamic').innerHtml = str.split('').join(':<br/>');
}
</script>
To recap some of the issues:
You can't document.write after the DOM has loaded. Doing so will generally only cause you frustration. Instead, as above, tweak the innerHtml or use a dozen other ways to change the DOM.
Set the button as type="button" instead of type="submit". Doing so will preclude either an actual form, or an implied one, from executing.
Your sendArray function didn't make any sense... but neither did most of the answers. Just make the string and set it somewhere, and iteration just isn't necessary here.
Ok I didn't expect to see so many incomplete answers. So let's summarize
The definition of the sendArray prototype function must not have parentheses
Above all, you don't need any sendArray prototype function (unless it is explicitly required by the Homework exercise)
You are passing a parameter to sendArray which you don't use inside the function
The action submit on the button will submit the form and hence refresh the page, so you won't see any other results of your code
You'll have to understand that pushing the button will use document.write, which will (after DOM loaded) always erase the previous document, including your script
Try it like this
<button type="button" onclick="show_alphabet()">Show alphabet</button>
<div id="output"></div>
<script type="text/javascript">
function show_alphabet() {
var str = new String("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
var arr = str.split("");
document.getElementById("output").innerHTML = arr.join(":<br/>");
}
</script>
sendArray = function() instead of sendArray() = function()
I have two variable and one function.
<script>
function myfunction(a1,a2,a3)
{
alert(a1+a2+a3)
}
var fname="myfunction";
var fdata="data1,data2,data3";
</script>
I want to call function from variable values. like this
myfunction('data1','data2','data3')
I know how to call function from variable value.
window[fname](); //this call myfunction()
But don't know how to call function with multiple arguments from variable values?
Give me a solution if you can!
First, you don't have to use the name of a function to keep a reference to it. Just use the function directly:
var fname = myfunction;
Then you can call it:
fname('whatever');
To pass parameters from that string, you'll have to get them out of the string, a process that will depend on how you've combined the values into a string in the first place. In your example, you could split the string on commas to create an array, and then use .apply()
fname.apply(null, fdata.split(','));
The .apply() method accepts an array as the second parameter (the first is a value to be used for this), and then calls the function such that the values of the arguments are the elements of the array.
Just add the arguments between the parentheses
window[fname]('data1', 'data2', 'data3');
To pass dynamically the arguments by using the fdata value, you should use apply (like #Pointy suggests).
window[fname].apply(null, fdata.split(','));
you can modify your code to be something like this maybe:
<script type="text/javascript">
function myfunction(a123) {
// remove the coma if you don't want it.
var completeData = a123.replace(/,/g, "");
alert(completeData);
}
var fname = "myfunction";
var fdata = "data1,data2,data3";
window[fname](fdata);
</script>
I hope it helps.
Here's the problem - I know function by name (and that function has already been loaded form an external script), but I don't have an actual function object avail for me to call. Normally I would call eval(function_name + "(arg1, arg2)"), but in my case I need to pass an object to it, not a string.
Simple example:
var div = document.getElementById('myDiv')
var func = "function_name" -- this function expects a DOM element passed, not id
How do I execute this function?
Thanks!
Andrey
Never use eval, it´s evil (see only one letter difference)
You can simply do:
var div = document.getElementById('myDiv');
var result = window[function_name](div);
This is possible because functions are first class objects in javascript, so you can acces them as you could with anyother variable. Note that this will also work for functions that want strings or anything as paramter:
var result = window[another_function_name]("string1", [1, "an array"]);
You should be able to get the function object from the top-level window. E.g.
var name = "function_name";
var func = window[name];
func( blah );