By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,222 Members | 1,436 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,222 IT Pros & Developers. It's quick & easy.

Can't change vars in JSON after consolidating lists into one

RMWChaos
100+
P: 137
Previously, I had used independent JSON lists in my code, where the lists were part of separate scripts. Because this method did not support reuse of a script without modification, I decided to consolidate all my JSON lists into one and modify my scripts so that they were more generic and reusable. So far so good.

The problem is that my JSON lists used variables for many pieces of code that performed multiple iterations to create several different but similar navigation and other buttons. So I created global vars that matched those in the JSON list, and my scripts would then redefine those vars according to what was the code was creating. Sounds logical.

It doesn't work. It's as if my scripts are not actually updating the global vars.

So the basic question is, how do I update vars in the JSON list (contained in a single .js file) from other scripts contained in their own .js files?

I am going to keep playing with this, but if anyone can help me out here, I would greatly appreciate it. Here is a quick visual example of what I am attempting to do.

Expand|Select|Wrap|Line Numbers
  1. // Example JSON list:
  2. var jList  =
  3.   {
  4.   'pageName'   :  ['pageOne', 'pageTwo', 'pageThree'],
  5.   'navigation' :
  6.     {
  7.     'dom'        :  'img',
  8.     'parent'     :  'body',
  9.     'id'         :  elementId,
  10.     'alt'        :  [altName, alreadyHere],
  11.     'title'      :  [altName, alreadyHere],
  12.     'src'        :  [pathDefault, pathSelected],
  13.     'onmouseover':  [mouseOver, null],
  14.     'onmouseout' :  [mouseOut, null],
  15.     'onclick'    :  [loadPage, navAlert],
  16.     }
  17.   }
  18.  
So as you can see, the only explicit values are in 'pageName' and in 'navigation', 'dom' and 'parent'. The rest are all vars or null. If this list were contained within a script that changed the vars, no problem. However, if the script instead modifies the vars of a JSON list not part of the script, then it doesn't seem to work.

Expand|Select|Wrap|Line Numbers
  1. /*
  2. * This snippet of code iterates through jList.pageName and sets the vars in
  3. * 'navigation'. Later code sends the updated 'navigation' lists to another
  4. * function for creating each page's nav buttons.
  5. */
  6. ...
  7. for (var index in jList.pageName)
  8.   {
  9.   var imageId = "nav" + index;
  10.   var divNavExist = document.getElementById(imageId);
  11.   var pathSelected = "../images/selected" + index.capitalize() + ".jpg";
  12.   var alreadyHere = 'You are already here.';
  13.   var navAlert = new Function("alert('You are already here.')");
  14.   var altName = "Jump to " + index.capitalize();
  15.   var pathHover = "../images/hover" + index.capitalize() + ".jpg";
  16.   var pathDefault = "../images/default" + index.capitalize() + ".jpg";
  17.   var mouseOver = new Function("mouseHover('" + pathHover + "', '" + imageId + "')");
  18.   var mouseOut = new Function("mouseHover('" + pathDefault + "', '" + imageId + "')");
  19.   var loadPage = new Function("logVerify(" + jList.pageName[index] + ")");
  20.   };
  21. ...
  22.  
When jList.pageName and jList.navigation were internal to this snippit of code, it all worked as designed. Now, it no longer updates the vars in the JSON list.

Thanks ahead of time for your help!
Dec 16 '07 #1
Share this Question
Share on Google+
19 Replies


gits
Expert Mod 5K+
P: 5,390
hi ...

in your second code-snippet ... what are you doing with all the newly created variables? do you assign them to your jList later on? or are they the 'globals'?

kind regards
Dec 17 '07 #2

RMWChaos
100+
P: 137
hi ...

in your second code-snippet ... what are you doing with all the newly created variables? do you assign them to your jList later on? or are they the 'globals'?

kind regards
I assign the values to the vars later on in my code. I attempted to make them globals so that the vars were declared at the beginning of my jList script like so:

Expand|Select|Wrap|Line Numbers
  1. var alreadyHere;
  2. var imageId;
  3. var altName;
  4. var pathHover;
  5. var pathDefault;
  6. var pathSelected;
  7. var mouseOver;
  8. var mouseOut;
  9. var loadpage;
  10. var navAlert;
  11.  
  12. var jList =
  13.     {
  14.     'navigation'  :
  15.         {
  16.         'dom'        :  'img',
  17.         'parent'     :  'body',
  18.         'id'         :  imageId,
  19.         'alt'        :  [altName, alreadyHere],
  20.         'title'      :  [altName, alreadyHere],
  21.         'src'        :  [pathDefault, pathSelected],
  22.         'onmouseover':  [mouseOver, null],
  23.         'onmouseout' :  [mouseOut, null],
  24.         'onclick'    :  [loadPage, navAlert],
  25.         },
  26.     ...
  27.     }
  28.  
Then in my scripts, I set the vars equal to some value: imageId = some code; etc. No errors occur, but looking at the DOMs with Firebug, the values are 'undefined'; so that is not working.

When you say, "...assign them to jList", do you mean using JSON code to insert data into the list? No, I have not tried that yet.

Perhaps I am doing something else basic wrong here with declaring global vars and assigning values to them later. As I understand it, a var is global when one of two conditions is true:

1. The var is declared outside of any function (i.e var myNewVar = someRandomValue;)

2. The var is declared inside a function without the 'var' assignment (i.e. myNewVar = someRandomValue;)

I prefer the first method.
Dec 17 '07 #3

gits
Expert Mod 5K+
P: 5,390
the problem with your current solution is that you assign the globals to the jList with undefined values. all of your global variables are simple datatypes and so they are passed by value to jList first. later on when you assign a value to such a variable the jList will not be updated, because it refers to the 'old' undefined value ... only arrays and objects are passed by reference in javascript ...

kind regards
Dec 17 '07 #4

RMWChaos
100+
P: 137
only arrays and objects are passed by reference in javascript
I've been wracking my brain and no solution yet. So can you clue me in as to where I might begin?

I'd rather not have to return to using smaller JSON lists inside each function, but I know that works. Once I get the basic structure of the website up, I still have the major part of the project to build a JSON-based forum board; so being able to use a centralized JSON list is important. I know basically how to permanently add and remove data from JSON lists, but not set vars within it if the list is entirely separate from the function.

You mentioned "assigning the vars to the JSON list." That sounds promising. Do you mean like this: "jList.memberName.element[value] = someValue;"? I will play with that for a while until I hear back from you.

Thanks!
Dec 19 '07 #5

gits
Expert Mod 5K+
P: 5,390
yep ... an explicit assignment would work and i think something like the following should work too:

Expand|Select|Wrap|Line Numbers
  1. var alt_properties = [];
  2.  
  3. var jList = {
  4.     'navigation': {
  5.         'dom'   : 'img',
  6.         'parent': 'body',
  7.         'alt'   : alt_properties
  8.     }
  9. };
  10.  
  11. alt_properties.push('test_0');
  12. alt_properties.push('test_1');
  13.  
  14. alert(jList.navigation.alt);
  15.  
kind regards
Dec 19 '07 #6

gits
Expert Mod 5K+
P: 5,390
ah and to have a look at your first solution ... a little bit simplified:

Expand|Select|Wrap|Line Numbers
  1. var alt_properties;
  2.  
  3. var jList = {
  4.     'navigation': {
  5.         'dom'   : 'img',
  6.         'parent': 'body',
  7.         'alt'   : alt_properties
  8.     }
  9. };
  10.  
  11. alt_properties = 2;
  12.  
  13. alert(jList.navigation.alt);
  14.  
and it will alert 'undefined' ...
Dec 19 '07 #7

RMWChaos
100+
P: 137
.push? .push... .push!

Okay, I have seen this used often in code I reviewed when looking for answers around the web. So I need to learn a little more about how this method works...

According to my sources, .push adds an element to the end of an array and returns the new length. Hm, not sure that is exactly what I want to do. Need more research...

Apparently there's more Array Object Methods: concat(), join(), pop(), reverse(), shift(), slice(), sort(), splice(), toSource(), toString(), unshift(), and valueOf().

I think maybe splice() is really what I need to use. According to my sources, splice "Removes and adds new elements to an Array (1)," which is more or less what I am trying to do. Then there is slice(), which is pretty much what I was trying to do with my whole splitAttribList() code. You could have just told me that and saved me a TON of trouble! =D

And then there are Array Object Properties, of which I know about index and length. There is also constructor, index, input, length, and prototype.

I've seen prototype a lot, but never knew what its purpose was. Now that I know what it's purpose is...I still don't understand it. :-|

Well, lots to study and learn and test! Back later with some results, and undoubtedly, more questions. ;-D

Thanks again, gits. You always save my arse! ;-D

Reference:
(1) www.w3schools.com (good starting reference and learning site, but some material is dated and no interactive forum like ITDN)
Dec 20 '07 #8

gits
Expert Mod 5K+
P: 5,390
it is the same as:

Expand|Select|Wrap|Line Numbers
  1. var a = [];
  2.  
  3. a[a.length] = 'something';
kind regards
Dec 20 '07 #9

RMWChaos
100+
P: 137
Oh, there you are! You read my post too soon. Should have waited until I edited it. =D

So your thoughts on push() versus splice()?
Dec 20 '07 #10

gits
Expert Mod 5K+
P: 5,390
hi ...

at first ... the methods are native ARRAY-methods ... so they only work with array not with objects like your jList is ...

push() and splice() have very different purposes ... so their use depends on your needs ;)

kind regards
Dec 20 '07 #11

gits
Expert Mod 5K+
P: 5,390
ah ... and i think for your purposes the following resource would be of more use than w3schools ... not to say that w3schools is bad ... but i think you are an mdc-man ;)

have a look here to start ... and then you will find nearly everything on MDC related to JavaScript ...

kind regards
Dec 20 '07 #12

RMWChaos
100+
P: 137
ah ... and i think for your purposes the following resource would be of more use than w3schools ... not to say that w3schools is bad ... but i think you are an mdc-man ;)

have a look here to start ... and then you will find nearly everything on MDC related to JavaScript ...

kind regards
You mean, evil, bastard! What have you done!? Parasitic Inheritance!? Object Augmentation!? Sugar!!!? I feel like a total newb again! Well, certainly an amateur at least. This is going to keep me busy for quite a while, and when all is said and done, I will (for the third time!) probably completely revise my web code.

You ever do this to me again, and I am booking the next flight to Germany to have a little "talk" with you. >:-(

Just kidding. Thanks for the reference, gits. Apparently, I still have a LOT of learning to do.
Dec 21 '07 #13

gits
Expert Mod 5K+
P: 5,390
*lol* ... did you even had a look at javascripts oo-posibilities? or why do you want to revise your code :) ... it would be a VERY good idea indeed but i don't know if it would be necessary for you and/or your current project? ...OO has many, many advantages even with complex projects that gains a lot of lines of code during time ... here we currently have about 400000 loc (javascript only!) checked in into the cvs ... it was nearly not to handle but with a slick oo-architecture-refactoring and a strict coding-guide we got back to be the masters over this bunch of code ... ;)

kind regards
Dec 21 '07 #14

RMWChaos
100+
P: 137
why do you want to revise your code :) ... it would be a VERY good idea indeed but i don't know if it would be necessary for you and/or your current project
Why would it be such a good idea? Just on principal to follow strict coding-guide, or because I am doing something fundamentally wrong with my current code? I really don't mind redoing my code. So far, this has just been a fun learning experience; although, I do have a purpose for the final website. No rush because it is a personal project.

*lol* ... did you even had a look at javascripts oo-posibilities? ...OO has many, many advantages even with complex projects that gains a lot of lines of code during time...with a slick oo-architecture-refactoring and a strict coding-guide we got back to be the masters over this bunch of code
No, I haven't looked at that yet. Still understanding some JS basic structures like Constructor, Prototype, private-type, and public-type. So far I have learned mostly by picking and choosing code that helps me do what I want to achieve, but if I want to do this project (and future projects) right, I need to fully understand what JS can do. So I will take a look at OO-possibilities next.

[RAMBLING]
The biggest part of my project is yet to come. As I've mentioned before, I am going to build a server-free, javascript-based forum using JSON (originally was going to use XML, but JSON is "fat-free" and accomplishes the same thing). This code will grow "naturally" as people post and reply, but my plan for that was to code an archiving process, which saves the post data to a search-able archive when it reaches a certain number of posts, minus the most recently active posts.

Why ever would I do such a thing!? Well, some of us do not have the cash to pay for a permanent domain/IP address, and despite that I have the servers here to host ASP or the like, I'm not sure that I want to go through the trouble of coding an IP address check/redirect process. But now that I think on it...use my ISP's web space to code the website, but the files are hosted locally on my server; then I code an IP address checker, which updates the website code with the new IP address automatically. The forum/message board would then be redirected each time the IP address changed. Hm, that is totally doable. Then I can use a standard Forum board...
[/RAMBLING]

So if OO-architecture-refactoring and a strict coding guide will keep my code streamlined, then I am all for it! =D

Danke!
Dec 21 '07 #15

gits
Expert Mod 5K+
P: 5,390
:) you pick the sentences from my post as you like ... nope ... you did well ... but using oop is always a good idea, even when you don't benefit from it yet you will do in the future ... believe me ... ;) it is a little bit more to do at the start of a project in case you would have to learn it meanwhile ... but in case you have it done ... you'll ask yourself: why didn't i use js oop before? ... the answer is: most people don't know about the very cool javascript that is a very underestimated programming language ... and they use it the script-kiddies cut&paste way ... and don't know about the concepts ... its good, because people have a quick success with their projects ... but its bad when someone has to maintain that snippet-like-code ...

there are very little good js-tutorials out there so most people that have a strong interest in javascript ... mostly the ones that are trying to build strict ajax applications ... have to learn it the hard way ... especially when using one of those ajax-frameworks out there you have to have a look at the js-core concepts to understand the frameworks and to be able to adapt things the way you need ...

i'm convinced that you'll do well ... and in case you have any questions pm me or post in the forum ... btw: interesting approach for your project ... keep up to let me know how it goes on :)

kind regards
Dec 21 '07 #16

RMWChaos
100+
P: 137
Okay, YES, I have heard of Object Oriented Programming before, but not exactly what that means or what it does--my background is in BASIC and COBOL, which are not OOP languages. Just in reading the explanation of what OOP is, I can already tell it is essentially what I was trying to accomplish with my "modular" code, and what you have been urging me to do all along with util-methods.

So I think you are correct, OOP is going to be a very good method of programming for me to understand and use.

What I really need here, though, are better code examples. I need real-world examples of the explanations that I am reading so that I can fully appreciate their meaning. That's how I've learned everything else I know about JS so far.

Will get back to you when I know more.
Dec 23 '07 #17

RMWChaos
100+
P: 137
Head spinning, brain hemorrhaging, losing all knowledge of programming...Java-what? What's a script?

Ugh.

Just had a crash-course in OOP, refactoring, and many, Many, MANY other concepts. Now what to do with it all...

Refactoring if conditional statements with polymorphism is a good thing!? AH!!!

I think you are testing my fortitude.
Dec 23 '07 #18

RMWChaos
100+
P: 137
Now to be controversial, I'm not yet convinced that OOP and refactoring are the best ways to program. (Don't laugh at my naiveté!)

What I mean is that I see the benefits to OOP and refactoring as they apply to maintaining code, particularly as code grows to huge proportions. So it is good for developers to read, share, and modify.

However, I am not sure that OOP and refactoring are good for code functionality. Does OOP/refactored programming run "faster" or more efficiently than procedural/structured programming? Does a machine really care one way or the other?

If the answer is, yes, oop/refactored programming is "faster" and/or more efficient to run than procedural/structured programming, then okay, I am sold. However, if the only benefit is to the developers, then I say no, I want another way to do this.

I know there are refactoring programs such as Bicycle Repair Man, which refactor code based on agile methodologies, but are their programs that do precisely the opposite: take refactored code and "optimize" it for runtime efficiency?

Writing code for human readability is essential, I agree, and minifying the code reduces its download footprint. But OOP and refactoring seem to me to potentially increase code length in some cases and create more functions that must be loaded into the global scope. I know we argued about this previously. Using util-methods decreases the chance for redundancy, and I agree with that. However, if the code is and always will pertain to a specific constructor or object, what is the benefit of splitting it out other than readability? Here is the classic human-vs.-computer needs, and is why we compile code from what a human understands to machine code.

Then again, perhaps this is just my flawed and incomplete understanding of OOP and refactoring. Or just the fact that it's 2:30 in the morning. 8-}

In any case, I must restate my goals, which at the moment appear to be in conflict: I want modular and fast/efficient code. OOP and refactoring meet the modular requirement, but do they impede, enhance, or have no effect on the fast/efficient requirement? If the answer is either "enhance" or "have no effect on", then I am all for OOP and refactoring.
Dec 23 '07 #19

RMWChaos
100+
P: 137
Well, this answer is ambiguous:
Some people may argue that certain compilers like SmallEiffel convert polymorphic calls into conditionals and that conditionals are faster and better than polymorphic calls. From a technical side it should be noticed that with polymorphic methods, the number of classes will not impact the performance whereas with nested conditionals the more classes that have to be type-checked, the more penalty you get. Then, although it is really justified for compilers to transform the code into faster forms — this is mainly why they exist, still this is not a justification to code like a compiler. The code we write is intended for developers, that’s why it should be readable, support abstraction and be more maintainable.
-Transform Conditionals to Polymorphism , p. 3
All this tells me is that there is still a need for "developer viewable code" and "runtime code." I am willing to script in the former, but I want my scripts to run in the latter.
Dec 23 '07 #20

Post your reply

Sign in to post your reply or Sign up for a free account.