How to access spring object list access in JavaScript - javascript

So I use Spring to pass a list of objects into the jsp, but I don't know how to access it's values and properties inside javascript.
So if I use something like:
var x = ${objectList};
there seems to be an error, when I use chrome to check it.
I would like to do something like this:
var x = ${objectList};
for(i=0; i<x.length; i++)
{
document.write(x[i].propertyName); // property for object i
}
I searched for an answer for a few days, but I didn't find one for my problem.

Try this to access spring object in javascript
<script>
var data=<c:out value="${objectList}"/>
</script>

Related

Adding Objects from Another File to an Array in a Separate File

I am trying to find a better solution for adding objects to an array. The box objects are from a separate file and are pushed to the array one line at a time in a different file, as such:
function loadCols(){
collisionPoints.push(box1);
collisionPoints.push(box2);
collisionPoints.push(box3);
collisionPoints.push(box4);
collisionPoints.push(box5);
collisionPoints.push(box6);
collisionPoints.push(box7);
collisionPoints.push(box8);
collisionPoints.push(box9);
collisionPoints.push(box10);
};
I have tried using a for loop and concatenating the string "box" + i but this didn't work.
I also tried adding them to an array in the file where the objects are created but I was not able to find a way of passing the array to the main file. Although this works I'm hoping there is a cleaner solution. Any help would be appreciated, cheers.
You can get a variable from it's string name, by using the window object.
function loadCols(){
for (var i=1; i<=numberOfBoxVars; i++) {
collisionPoints.push(window["box" + i]);
}
}
Alternatively, if your variable are defined within a closure and your loadCols function is defined within the same closure, you can use the "this" keyword in place of the window object.
(function() {
var box1 = "1";
var box2 = "2";
...
function loadCols(){
for (var i=1; i<=numberOfBoxVars; i++) {
collisionPoints.push(this["box" + i]);
}
}
});
If I understand you correctly you are looking for a way to use dynamic variables in a for-loop. If box1 and so on are global variables you can get them dynamically by accessing them as property of window:
window['box'+i]
See here: Use dynamic variable names in JavaScript
If you send all the objects in a JSON array you could just do this:
var array = JSON.parse(boxesarray);
for(var i = 0;i< array.length; i++) {
collisionPoints.push(array[i]);
}
But it would require you sending all the boxes in an array, if this is not possible please post code as to why it isn't and i will adapt my anwser.

How do I call a jQuery function with a dynamic name?

I can't believe that I've been unable to dig out a solution to this problem. It looked to me like a very "regular" problem whose solution would litter the web!
I have these arrays returned from a database query:
var ids = ['12', '15', '40'];
var actions = ['hide', 'show', 'fadeIn'];
I want to loop through the arrays and carry out the appropriate action on the DOM, like so:
for(var i=0; i < ids.length; i++){
$('#row_'+ids[i]).actions[i]();
}
Now you get the idea. Actually I didn't expect the $('#row_'+ids[i]).actions[i](); to work as is. I have tried things like
$('#row_'+ids[i]).effect(actions[i]);
To no avail. I believe eval() should work and (in desperation) even tried that but couldn't get the right string for it to work.
Elsewhere on Stack Overflow, I have come across similar issues solved using the window global, like:
var fn = 'hideSomething';
window.fn();//where hideSomething was a defined function.
But this one is defined on jQuery, not on window.
So here we are!
You need to use [varhere] to access a property/method by variable name. Since your property name is in actions[i], then you would do this:
$('#row_'+ids[i])[actions[i]]();
Or, in a slightly easier scheme to follow exactly what is happening:
var method = actions[i];
$('#row_'+ids[i])[method]();
You can use the dot syntax obj.prop when the property name is known ahead of time. When it's in a variable and not known ahead of time, you use the obj[prop] syntax. Since a method is just a property, the same applies to jQuery methods too.
for(var i=0; i < ids.length; i++){
$('#row_'+ids[i])[actions[i]]();
}
Use square bracket notation in order to access the property:
for (var i = 0; i < ids.length; i++) {
$('#row_' + ids[i])[actions[i]]();
}
Example Here
See: Property accessors in JS (MDN)

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

Defining variables dynamically in Javascript

In a situation where I have something like this code:
var variableNames=["thisMonth", "thisDay"];
var variableValues=["February", 17];
Is there any way I could go through the array and initiate variables with their corresponding values? I've tried something like
for(var i=0;i<variableNames.length;i++){
eval("var "+variableNames[i]+"="+variableValues[i]+";");
}
But I'm not getting any reults. Is eval not able to define variables, or are there other problems that exist? Any solution would be greatly appreciated.
You need to assign the variables on an object. If you want to create global variables the following code should work:
for (var i=0; i<variableNames.length; i++) {
window[variableNames[i]] = variableValues[i];
}
//test
console.log(thisMonth); //"February"
Here you go. You missed a couple of quotes at "='" + variableValues[i] + "';");:
var variableNames=["thisMonth", "thisDay"];
var variableValues=["February", 17];
for(var i=0;i<variableNames.length;i++){
eval("var "+variableNames[i]+"='"+variableValues[i]+"';");
}
With that correction however, I would warn you against using it cause it's a very wrong way of doing it.
Use Objects, as most here mention.

how to pass a function name via JSON and call it in javascript/jQuery?

I have a JSON string which includes a function I need to call.
My JSON looks like this:
{
"type":"listview",
// the function I would like to call
"content":"dynoData.getRetailers()",
"custom_classes":["","nMT pickList","",""],
"lib":"static_listview.html",
"tmp":"tmp_listview_inset",
"lang":"locale_search",
...
I'm using this to assemble a jQuery Mobile listview on the client. To get the dynamic data, I need to call dynoData.getRetailers().
However I'm struggling to make the call :-)
This is what I'm trying:
var dyn = $.parseJSON( passed_JSON_string ),
content = dyn.content;
I had hoped calling it would trigger the function but it just returns the function name as a string.
Question:
How can trigger the actual function?
Thanks!
EDIT:
I'm putting the JSON string on the HTML element on the actual page, which I will replace with the element I'm building. Here is the HTML:
<ul data-template="true" data-config='{
"type":"listview",
"content":"dynoData.getRetailers()",
"custom_classes":["","nMT pickList","",""],
"lib":"static_listview.html",
"tmp":"tmp_listview_inset",
"lang":"locale_search",
"theme":"c",
"filter":"true"
}'></ul>
I could put all of these into data- attributes, but that would be messy...
Solution:
This worked:
1) change JSON to:
..."method":"getRetailers", ...
2) call from Javascript:
content = dynoData[ dyn.method ]();
Thanks everyone!
Assuming the function is always part of the dyn object you can use notation like following to call a function:
dyn['dynoData']['getRetailers']();
So if you are able to adjust json you could send back something like:
"content":{ "mainObject": "dynoData" , "method" :"getRetailers"}
And translate it to your dynamic function using variables:
dyn[content.mainObject][content.method]();
As an example using jQuery try using the following :
$('div')['hide']();
Which is the same as :
$('div').hide()
As charlietfl pointed out you can use object notation to call functions. For your case you have to get rid off () and split it, then call it like this;
jQuery(function($) {
var temp = $('ul').data('config').content.replace(/\(\)/g, '').split('.');
window[temp[0]][temp[1]]();
});
However this could solve your problem, if you think about future, you have to extend it a little bit. This way even you don't know the depth, you can call it anyway;
jQuery(function($) {
var temp = $('ul').data('config').content.replace(/\(\)/g, '').split('.'), func, i, il = temp.length;
for(i = 0; i < il; i++) {
if(func == null) {
func = window[temp[i]];
continue;
}
func = func[temp[i]];
}
func();
});
Try ConversationJS. It makes dynamic calls pretty easy and its a great way to decouple your codebase: https://github.com/rhyneandrew/Conversation.JS
JSON is purely data notation to be passed around so it is easily read and parsed, therefore it has no concept of functions. However, there are other ways of dealing with this and if you are starting to think that that is the only way to deal with your dilemma, then take a step back and examine your design. Instead of using this:
eval(yourCode);
Try this
var tempFun = new Function(yourCode);
tempFun();

Categories

Resources