Need to get an array of the names of all applicationScope variables - javascript

In an application I am working on I need to get a list of the names of all applicationScope variable then I need to cycle through them and filter out the ones starting with a know string say $xyx. I thought that the applicationScope.keySet().
I'm using this code for starter:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
if (itr.hasNext()){
var str:String = itr.next();
dBar.info(str,"Value = ");
}
if I put the variable col in a viewScope it shows a list of all the keys. but when I run the script the values displayed in the dBar info are not the keys but some other information that I'm not sure where it comes from.
I should just be able to iterat through the list of keys, am I missing something?
This code is in the before page loads event

After some poking around and experimenting I got this to work:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
while (itr.hasNext()){
var str:Map.Entry = itr.next();
if (str.substring(0,9) == "$wfsLock_"){
//do stuff
}
}
so I'm now a happy camper.

Although your code works in SSJS, it is not correct (and that's why I don't like SSJS...).
The applicationScope is an implementation of the java.util.Map interface and the keySet() method returns a Set containing the keys in that Map. Every entry is (probably) a String (other data types like integers are actually also valid). The line
var str:Map.Entry = itr.next();
doesn't cast it to a Map.Entry: it doesn't really do anything: str remains a string.
The Map interface also has an entrySet() method that returns the entries (Map.Entry). You can use that to retrieve the key as well as the value:
var it = applicationScope.entrySet().iterator();
while (it.hasNext()) {
var entry = it.next();
print( entry.getKey() + " = " + entry.getValue() );
}
(in this code the print() line will use the toString() method of the key as well as the value to send information to the console)
I see from your code that you've installed my XPages Debug Toolbar. You can also use that to quickly check what's in the scopes and what the actual datatype is.

Related

Searching a string

OK Ive been able to get the following to partially work
var Global_Wound_array =[{"WoundNumber":1,"BodySide":"Front","BodyPart":"Nose"},{"WoundNumber":2,"BodySide":"Left","BodyPart":"Head"},{"WoundNumber":3,"BodySide":"Back","BodyPart":"Ear"}]
var Global_Wound_Counter = 1
I can get the page to loop through and display the individual wounds but I need a way to say at a particular page one of the values eg on WoundNumber 2 BodyPart has changed and updated the string without affecting the rest of it.
page9200.setEventHandler("pageFinishing", function () {
//getSelectedButtonLabel this is ok - specific on the system
let Q1 = Q3_WoundNumber.getValue();
let Q2 = Q1_BodySide.getSelectedButtonLabel();
let Q3 = Q2_BodyPart.getSelectedButtonLabel();
for (var i = 0; i < Global_Wound_array.length; i++) {
if (i+1 == Q1){
//create new temp variable array
var Temp_Wound_obj2 = {"WoundNumber": Q1,"BodySide": Q2,"BodyPart":Q3}
Global_Wound_array.push(Temp_Wound_obj2)
}
}
});
As well as being able to reach the end of the string to present a blank set of values to have the option to add a new wound.
Every time I think Ive got something that looks like it would work I go around in circles, when I try to update the system at the end I get and error that the - invaid parameters for RPC call: variable is bad
It seems you are pasting JSON onto JSON, with no separator. This creates a messy and non-standard data structure. If you wrote your JSON with a newline at the end, you would end up with a JSONL file, which is very simple to process.
const jsonl = `
[{"WCount":1,"Side":"Centre","Part":"Ocipit","Type":"Other","SurroundingSkin":"Dermatitis","Height":"","Width":"","Depth":""}]
[{"WCount":2,"Side":"Front","Part":"Neck","Type":"Diabetic foot wound","SurroundingSkin":"Healthy/intact","Height":"3","Width":"4","Depth":"5"}]
`;
const jsonItems = jsonl.trim().split("\n");
const lastJsonItem = jsonItems[jsonItems.length - 1];
const lastItem = JSON.parse(lastJsonItem);
const lastWCount = lastItem[0].WCount;
console.log(lastWCount);
If you already have a file without newlines... it would be best to insert them, and correct your data to JSONL. This is simple in your case just by replacing ][ with ]\n[ (and making sure the file ends with a newline too, so the next write would not be messed up), since you have no nesting and (hopefully) no ][ in your text, but in general it is not easy - I don't know of a JSON parser that will return unconsumed text, so it would probably involve writing a JSON parser. Much easier to write data correctly in the first place.

Java Script + JSON Parsing and converting into Array

I'm looking for help in converting a particular elements in JSON message to an array using java script at run time. We wanted the script to be more generic. Actually we were trying the following which worked for single element and while changing it to handle for multiple elements at run time its not working.
//Working for Single element - Static
var bodyContext = JSON.parse(response.content)
if(bodyContext.companylist.company.constructor !== Array){
bodyContext.companylist.company = [bodyContext.companylist.company]
}
The above code works and converts Company in JSON message as a Array, Where as the below we tried for multiple elements is not working
//Not Working for multiple elements - dynamic
var bodyContext = JSON.parse(response.content)
var elementName = "";
//Loop runs every time and changes the value of elementName at every iteration
if(bodyContext.elementName .constructor !== Array){ //not working
bodyContext.elementName = [bodyContext.elementName] //Not working
}
instead of looking for "bodyContext.companylist.company" and converting into Array, "bodyContext.elementName" is checked and added to the bodycontext object.
how to handle this. ElementName variable along with JavaScript object is not recognized.
Please help.
you can JSON.parse(data) then you can fetch data from Javascript object like
$.each(Obj,function(key,value){
});
You'll want to use
bodyContext[elementName]
since
bodyContext.elementName
looks for a field in bodyContext named elementName, not the a field named after the value in elementName.
Also, you initialize elementName with "", and this won't match anything on the first iteration.

Having trouble referring to object within array

I am trying to write an html page for class that uses a drop down menu to allow users to pull up a list of relevant information. Unfortunately I am having trouble figuring out how to make the script call on the information in the array. The jsfiddle has the full html section, any help would be GREATLY appreciated.
Please bear in mind that I am not very good with terminology, so be as specific as possible. Especially regarding jQuery, our teacher didn't go over it much so it's a freaking mystery to me.
Also, I do plan on adding more information to the objects in the array, but until I get it working, I don't want to waste the time on something I might need to restructure.
http://jsfiddle.net/GamerGorman20/nw8Ln6ha/11/
var favWebComics = [
Goblins = {1: "www.goblinscomic.org"},
GirlGenious = {1: "www.girlgeniousonline.com"},
GrrlPower = {1: "www.grrlpowercomic.com"}
];
var myFunction = function() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
document.getElementById("web").innerHTML = favWebComics.x;
};
Again, the JSFiddle link has the full html, there are some unused items currently, but I do plan on adding more of them soon.
My next plan is to incorporate images into the objects, so a picture loads for each selection option. How would I manage that?
[ ] is used for arrays, which are indexed with numbers. If you want named properties, you should use an object, which uses { } for its literals:
var favWebComics = {
Goblins: "www.goblinscomic.org",
GirlGenious: "www.girlgeniousonline.com",
GrrlPower: "www.grrlpowercomic.com"
};
= is for assigning to variables, not specifying property names in an object.
Then you need to understand the difference between . and [] notation for accessing objects. .x means to look for a property literally named x, [x] means to use the value of x as the property name. See Dynamically access object property using variable.
So it should be:
document.getElementById("web").innerHTML = favWebComics[x];
your array is not structured correctly and an object would be better suited:
var favWebComics = {
Goblins : "www.goblinscomic.org",
GirlGenious : "www.girlgeniousonline.com",
GrrlPower : "www.grrlpowercomic.com"
};
then you should be able to access the properties as you intend
favWebComics.Goblins
favWebComics.GirlGenious
favWebComics.GrrlPower
Technically you were treating the array like a dictionary. if you're going to do that but still wanna add more information later you'll need to use brackets {} on the code.
var favWebComics = {
Goblins: ["www.goblinscomic.org"],
GirlGenious: ["www.girlgeniousonline.com"],
GrrlPower: ["www.grrlpowercomic.com"]
};
Also for javascript, as long as your searching key value stores, use braces [] for the call. Here's the working code below.
document.getElementById("web").innerHTML = favWebComics[x];
I have your solution, that displays:
the selected choice
the url
the images
Please check the fiddle.
http://jsfiddle.net/nw8Ln6ha/13/
Your object would be:
var favWebComics = {
Goblins : {url:"www.goblinscomic.org", img:"img1"},
GirlGenious : {url:"www.girlgeniousonline.com", img:"img2"},
GrrlPower : {url:"www.grrlpowercomic.com", img:"img3"}
};
Your display code:
document.getElementById("demo").innerHTML = "You selected: "+x+" "+ eval("favWebComics[\""+x+"\"].url")+" "+ eval("favWebComics[\""+x+"\"].img");

Get console.log() to display custom object description

I have a custom JS object that I've made to represent a grid. Stripped down for this example it looks like this:
function Grid(c, r)
{
var layout = [];
var contentPointer = 0;
this.getCell = function(c, r)
{
//Return selected cell
}
this.getRow = function(r)
{
//Return selected row
}
this.getCol = function(c)
{
//Return selected column
}
for(var row = 0; row < r; row++)
{
layout[row] = [];
for(var col = 0; col < c; col++)
layout[row][col] = 0;
}
}
I'm creating multiple instances of this here and there using var aGrid = new Grid(10, 10); and then manipulating them in various ways; adding/updating the contents of cells etc.
What I would like to be able to do is call console.log(aGrid); and be able to customise what is displayed by the console so I get, for instance, a string of all the cell values I've added or something similar.
In am used to Actionscript where we would use trace(aGrid); in place of console.log(aGrid); but in AS3 I could override the object's toString() method and that would update what is shown in the console output.
I have seen that I can add a toString() method to my Grid object in JS but the console does not seem to use it unless I specifically call console.log(aGrid.toString());. While this is fine, I just wondered if there is a way round this.
Does the console actually generate it's output based on some overridable method of the object being logged or does it do some crazy internal magic to get a value?
using alert(aGrid); seems to use toString() and picks up the custom value but I would rather peel my own skin off than debug a big project using alert(); :)
Any and all comments very welcome. Thank you.
PS - I don't know if different browsers treat console.log() differently but I am using Chrome v33.
I have seen that I can add a toString() method to my Grid object in JS but the console does not seem to use it unless I specifically call console.log(aGrid.toString());. While this is fine, I just wondered if there is a way round this
No, there is no way around this. The console alone does decide how to display the passed arguments - and Chrome console lets you dynamically inspect objects instead of trying to serialize them somehow. If you want a custom output, you will need to pass it a string.
console.log accepts Object as argument(s), and if you put it there, you will be able to inspect it in Chrome console.
So remove .toString() and it will do the trick
console.log("aGird", aGrid );
You can use console.table() for this. console.table allows you to specify what properties would you like to view. For instance
console.table(aGrid); // will show all properties
console.table(aGrid, 'firstName'); // will show only firstName property
console.table(aGrid, ['firstName', 'lastName']); // will show firstName and lastName properties

Pass in vars to an eval workaround to process a code string from a json object after YUI compression

I need to pass a jQuery object in to a workaround for an eval. The issue is that i need access to a jQuery object that is out side the eval area but i can't see to pass it in. here is what i have.
var jObj = $(selector);
var myCode = "var jObj="+jObj+"; var i="+i+"; "+shape.mouseover.onEnd.replace("\u0027","'");
var myFucn = new Function(myCode);
myFucn();
the oject I'm getting the string out of is
shape.mouseover.onEnd.replace("\u0027","'");
is working and what I'm passing in that string is
open_info(jObj,i)
Which is what i have to fire. The deal is that the code is run thru YUI compressor so the jObj var becomes something else so i need to pass that in. Right now i get an error where it thinks it should have and ending ] which is not right. I is working it seems, just not the jObj var.
EDIT
there are many way to get where i need to be that are close but not quite like
How to pass parameters in eval in an object form?
shape.mouseover.onEnd = "open_info(jObj,i)";
/*
* this is coming in and must be as it is, don't say it's wrong please
* it's not able to be done anyother way!
*/
//lets process the string and pull in the vars
/* BEOFRE YUI COMPRESSOR CHANGES THINGS and works!!!
var jObj = $(selector);
var i = 1;
var myCode = shape.style.events.mouseover.onEnd.replace("\u0027","'");
var myFucn = new Function(myCode);
myFucn();
*/
// AFTER note it can be random as i change code so it fails cause
// var jObj is now var r and var i is now var e
var r = $(selector);
var e = 1;
var p= shape.style.events.mouseover.onEnd.replace("\u0027","'");
var f= new Function(p);
f();
Now it works before the compression.. After is not due to the change. Hope tha tclears it up some
I might be going down the wrong tracks and be confused here..
But isnt this what your trying to do?
Send myFucn the correct object and what ever i is
myFucn($(selector),10);
function myFucn(jObj,i)
{
shape.mouseover.onEnd.replace("\u0027","'");
}
I still don't understand why this question got 2 down votes, but well it's solved and works great. The trick is to do the same manipulation of the dom state. It's really simple once it is placed out.
//so this is what the object is parsed out to from the json string
//since you can't just pass a function stright that way any how
shape.mouseover.onEnd = "open_info(jObj,i)";
//this is what will take that string and process it
//note jObj is what is in the orgain code but it changes to
// var r or something else that is shorter after going thru YUI compressor
// Which is why we can't just use open_info(jObj,i) and it work..
// ie: it's not an issue with scoope but an issues with var names being shortened
(function(){
//this is the trick on passing them so YUI doesn't get them
//use a string and YUI skips it so we directly create the
//needed oject in the window namespace
window['jObj']=jObj; window['i']=i;
var p= shape.mouseover.onEnd;
var f= new Function(p);
f();
})();
That is it.. I put it in a click or hover event so it's kin to an onClick.
/* EXMAPLE OUTPUT AFTER YUI COMPRESSION
//Note after the YUI compressor get ahold of that
//processing code above it'll look like
*/
function(){window.jObj=n,window.i=t;var u=i.mouseover.onEnd,r=new Function(u);r()}();
So the way that works is, I needed to fix the issue of the var jObj being renamed. So I simply made a sting for the name and let the compressed the var name fill the name of the object I need for the processed code string. Don’t know why I didn’t see it before and I would have saved my rep value :-\ .. oh well. May be a way to shorten this but I'm leaving it for now.
Edit
I recant the edit it was working. :) Very well.. Left wondering what any other ways there would be to make it do the same thing.

Categories

Resources