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];
}
});
Related
I have a function:
function hello(param){ console.log('param is '+param); }
And two calls. First:
hello(123)
Second:
var a=123; hello(a);
Is there any possible way to tell, from within the hello function, whether param was passed as a var or as a literal value?
NOTICE: I am not trying to solve a problem by this. There are many workarounds of course, I merely wanted to create a nice looking logging function. And also wanted to learn the boundaries of JavaScript. I had this idea, because in JavaScript we have strange and unexpected features, like the ability to obtain function parameter names by calling: function.toString and parsing the text that is returned.
No, primitives like numbers are passed by value in Javascript. The value is copied over for the function, and has no ties to the original.
Edit: How about using an object wrapper to achieve something like this? I'm not sure what you are trying to do exactly.
You could define an array containing objects that you want to keep track of, and check if its in there:
var registry = [] // empty registry
function declareThing(thing){
var arg = { value: thing } // wrap parameter in an object
registry.push(arg) // register object
return arg; //return obj
}
function isRegistered(thingObj){
return (registry.indexOf(thingObj) > -1)
}
var a = declareThing(123);
hello(a);
function hello(param){
console.log(isRegistered(param));
}
I am trying to click on the first radio button and it will assign variables distSelected and weapon some values from the object engDistanceObject. I suspect my HTML might not be written correctly... specifically the input tags.
https://jsfiddle.net/Natronox/sbojaxm4/#&togetherjs=zb80KxkQzm
var engDistanceObject = {
short: ["100m-300m","416 Assault Rifle"],
long: ["300m-1000m","M110 DMR"]
};
var distSelected;
var weapon;
function distanceClick(item){
distSelected = engDistanceObject.item[0];
weapon = engDistanceObject.item[1];
console.log(distSelected,weapon);
};
Use your short and long properties instead of item. You don't have an item property name in your object.
.short[0]
.short[1]
To access dynamic properties, you can't use the . syntax. It ignores variables that might have the same name as the property you're trying to access, and instead will try to access the non-existent item property.
Instead, use the bracket syntax [], which allow a string to be used to access dynamic properties. This means that you need to pass a string as a parameter to your function.
Your HTML event handlers will need quotes around the parameters:
onclick="distanceClick('long')"
And then use the bracket syntax in your JS:
function distanceClick(item){
distSelected = engDistanceObject[item][0];
weapon = engDistanceObject[item][1];
console.log(distSelected, weapon);
}
I have one function in which I am iterating across data object which I have fetched from database. In the foreach loop I am trying to create one object(trigger) and pushing it to another variable(Geo) which I will use to put in another variable(triggers). Below is the code-
var Geo={};
array.forEach(this.cityData,lang.hitch(this, function(data,i){
var trigger = {
type: "Inside",
event: {
name: data.Name,
address:data.Address
}
};
var Location= "Location_"+i;
Geo.Location=trigger; // pushing trigger in Geo variable
}));
var triggers = {
Geo //using Geo in trigger
};
is var triggers={Geo}; equivalent to this below code ?
And is my pushing code Geo.Location=trigger; correct ?
var triggers = {
Geo: {
Location_1: trigger1,
Location_2: trigger2 ...... and so on...
}
};
I didn't tested it but it looks like it does almost the same.
Just one thing:
This should give you an exception:
var triggers = {
Geo //using Geo in trigger
};
The statement should be
var triggers = {
'Geo': Geo //using Geo in trigger
};
otherwise triggers will not have a Geo property.
Geo.Location=trigger; is just fine.
A property in an object accessed through dot notation (obj.property) is always considered simply as the propoerty name - i.e. variables are not evaluated. You can have dynamic property names by using the bracket notation: obj[property], which convert "property" to a string (resolving the variable value if necessary) and uses that as the actual property name.
So, try changin:
Geo.Location
to:
Geo[Location]
Edit: I'm not sure what is the expected final result, but if you want to achieve an object as shown in your last code block, the correct syntax should be:
triggers.Geo = Geo;
again, in consideration of the fact that the "Geo" in the dot notation form is simply the string name of the property, and has no relation to the variable of the same name.
i want to create a dynamic generated form using javascript, everything works fine, until i try to pass an array as parameter. When i do this, an error happens. Coulr anyone explain what this is?
Heres my code:
var loadFrm = function(component) {
for(nItem in component) {
var myComponent = "add" + firstToUpper(component[nItem].type);
var callComponent = myComponent + "(" + component[nItem].opt + ");";
eval(callComponent);
}
}
var json = [
{
type: "scale",
opt: {content: [{label: "male", value: "m"}, {label: "female", value: "f"}]}
}
];
loadFrm(json);
Edit Here's the error:
missing ] after element list
[Break on this error] addScale([object Object]);
If you use a debugger to look at the string callComponent, you'll probably find it looks something like this:
addScale([object Object])
...which isn't what you want. That's because you're effectively calling toString on your opt object, and the default toString on objects just looks like that. The eval error is because that's invalid syntax.
Generally speaking, any time you think you need to use eval, there's almost certainly a better answer. In this case, it looks like you're trying to call a function and pass in opt. Assuming these functions are "globals", you can do that like this:
var loadFrm = function(component) {
var nItem, functionName;
for (nItem = 0; nItem < component.length; ++nItem) {
functionName = "add" + firstToUpper(component[nItem].type);
window[functionName](component[nItem].opt);
}
}
Live example
Notes on the above:
Don't use for..in to loop through arrays unless you really know what you're doing. for..in does not enumerate the indexes of an array, it enumerates the properties of an object.
We look up the function by name using window[functionName]. This works because "globals" are actually properties of the window object, and you can look up properties using a string name for them using bracketed notation.
Having gotten the function via window[functionName], we just call it directly, passing in the object opt rather than a string form of it. I assume addScale expects to see an object.
I moved all of the vars to the top of the function because that's where they really are (details).
If you can, I'd recommend moving addScale and the related functions to their own object rather than putting them on window. The window namespace is already pretty crowded. Here's the live example modified to not add any symbols to window at all, instead putting the addScale function on an object called functions and using it from there.
Off-topic: The syntax var loadFrm = function(component) creates an anonymous function that it then assigns to a variable. This is used a lot, but unless you're creating different functions based on a condition, e.g.:
var f;
if (...) {
f = function() { ... };
}
else {
f = function() { ... };
}
...it's not actually useful. (If you are creating different functions based on a condition like that, then it's not only useful, it's necessary.) I recommend using named functions whenever possible, because a function with a name helps your tools help you by showing you the function name in error messages, call stacks, etc.
Off-topic 2: You have a variable called json, but FYI, it's not using JSON notation. It's using a combination of JavaScript array and object literal notation, which is a superset of JSON. You'll see a lot of people confused about this, I mention it because you said you're new and so it's worth nipping in the bud. :-) JSON is purely a notation. (A very useful one.)
Use this:
fn = eval(functionName);
fn(objParameter)
someFunction(link) {
someOtherFunction('div' + link);
}
By calling someFunction("Test"), the string "divTest" gets passed to someOtherFunction(). But I want the value of the variable "divTest" to be passed.
How can that be done?
Make your variables members of an object. Then you can use [] to access the objects members using a string:
var byname = {
divabc: ...,
divxyz: ...
};
function someFunction(link) {
someOtherFunction(byname['div'+link]);
}
someFunction('abc'); // calls someOtherFunction(byname.divabc)
For this kind of dynamic construction/access of variable names you should use the alternative object notation where:
object.member === object["member"]
This way you could construct your variable name as a string and use it inside square brackets for accessing object members.
eval will do this, but it's usually indicative of some other problem with the program when you want to synthesize identifiers like this. As Ionut says it's better to use the [] notation. I like to link to this whenever questions like this come up.
You should be able to accomplish this with the 'eval' function.
Try this:
var divFoo = "bar";
function someFunction(link) {
someOtherFunction(this['div' + link]);
}
function someOtherFunction(value) {
alert(value);
}
someFunction("Foo");
As wybiral said, all you need is eval:
someFunction(link) {
someOtherFunction(eval('(div' + link + ')');
}
Basically what it does is evaluates the contents of a string as code. Obviously eval is a dangerous little tool since it allows executing arbitrary code so take care when using it.