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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • RMWChaos
    New Member
    • Oct 2007
    • 137

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

    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.

    [code=javascript]
    // Example JSON list:
    var jList =
    {
    'pageName' : ['pageOne', 'pageTwo', 'pageThree'],
    'navigation' :
    {
    'dom' : 'img',
    'parent' : 'body',
    'id' : elementId,
    'alt' : [altName, alreadyHere],
    'title' : [altName, alreadyHere],
    'src' : [pathDefault, pathSelected],
    'onmouseover': [mouseOver, null],
    'onmouseout' : [mouseOut, null],
    'onclick' : [loadPage, navAlert],
    }
    }
    [/code]
    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.

    [code=javascript]
    /*
    * This snippet of code iterates through jList.pageName and sets the vars in
    * 'navigation'. Later code sends the updated 'navigation' lists to another
    * function for creating each page's nav buttons.
    */
    ...
    for (var index in jList.pageName)
    {
    var imageId = "nav" + index;
    var divNavExist = document.getEle mentById(imageI d);
    var pathSelected = "../images/selected" + index.capitaliz e() + ".jpg";
    var alreadyHere = 'You are already here.';
    var navAlert = new Function("alert ('You are already here.')");
    var altName = "Jump to " + index.capitaliz e();
    var pathHover = "../images/hover" + index.capitaliz e() + ".jpg";
    var pathDefault = "../images/default" + index.capitaliz e() + ".jpg";
    var mouseOver = new Function("mouse Hover('" + pathHover + "', '" + imageId + "')");
    var mouseOut = new Function("mouse Hover('" + pathDefault + "', '" + imageId + "')");
    var loadPage = new Function("logVe rify(" + jList.pageName[index] + ")");
    };
    ...
    [/code]
    When jList.pageName and jList.navigatio n 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!
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    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

    Comment

    • RMWChaos
      New Member
      • Oct 2007
      • 137

      #3
      Originally posted by gits
      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:

      [code=javascript]
      var alreadyHere;
      var imageId;
      var altName;
      var pathHover;
      var pathDefault;
      var pathSelected;
      var mouseOver;
      var mouseOut;
      var loadpage;
      var navAlert;

      var jList =
      {
      'navigation' :
      {
      'dom' : 'img',
      'parent' : 'body',
      'id' : imageId,
      'alt' : [altName, alreadyHere],
      'title' : [altName, alreadyHere],
      'src' : [pathDefault, pathSelected],
      'onmouseover': [mouseOver, null],
      'onmouseout' : [mouseOut, null],
      'onclick' : [loadPage, navAlert],
      },
      ...
      }
      [/code]

      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.

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5390

        #4
        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

        Comment

        • RMWChaos
          New Member
          • Oct 2007
          • 137

          #5
          Originally posted by gits
          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.memberNam e.element[value] = someValue;"? I will play with that for a while until I hear back from you.

          Thanks!

          Comment

          • gits
            Recognized Expert Moderator Expert
            • May 2007
            • 5390

            #6
            yep ... an explicit assignment would work and i think something like the following should work too:

            [code=javascript]
            var alt_properties = [];

            var jList = {
            'navigation': {
            'dom' : 'img',
            'parent': 'body',
            'alt' : alt_properties
            }
            };

            alt_properties. push('test_0');
            alt_properties. push('test_1');

            alert(jList.nav igation.alt);
            [/code]
            kind regards

            Comment

            • gits
              Recognized Expert Moderator Expert
              • May 2007
              • 5390

              #7
              ah and to have a look at your first solution ... a little bit simplified:

              [CODE=javascript]var alt_properties;

              var jList = {
              'navigation': {
              'dom' : 'img',
              'parent': 'body',
              'alt' : alt_properties
              }
              };

              alt_properties = 2;

              alert(jList.nav igation.alt);
              [/CODE]
              and it will alert 'undefined' ...

              Comment

              • RMWChaos
                New Member
                • Oct 2007
                • 137

                #8
                .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)
                Last edited by RMWChaos; Dec 20 '07, 04:21 PM. Reason: Additional Research

                Comment

                • gits
                  Recognized Expert Moderator Expert
                  • May 2007
                  • 5390

                  #9
                  it is the same as:

                  [CODE=javascript]var a = [];

                  a[a.length] = 'something';[/CODE]
                  kind regards

                  Comment

                  • RMWChaos
                    New Member
                    • Oct 2007
                    • 137

                    #10
                    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()?

                    Comment

                    • gits
                      Recognized Expert Moderator Expert
                      • May 2007
                      • 5390

                      #11
                      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

                      Comment

                      • gits
                        Recognized Expert Moderator Expert
                        • May 2007
                        • 5390

                        #12
                        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

                        Comment

                        • RMWChaos
                          New Member
                          • Oct 2007
                          • 137

                          #13
                          Originally posted by gits
                          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.

                          Comment

                          • gits
                            Recognized Expert Moderator Expert
                            • May 2007
                            • 5390

                            #14
                            *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

                            Comment

                            • RMWChaos
                              New Member
                              • Oct 2007
                              • 137

                              #15
                              Originally posted by gits
                              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.

                              Originally posted by gits
                              *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!

                              Comment

                              Working...