JavaScript newbie: Need help in working with objects

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • paragpdoke
    New Member
    • Dec 2007
    • 62

    JavaScript newbie: Need help in working with objects

    Hello Everyone. Merry Christmas to all !
    I'm a JavaScript newbie (and new to thescripts.com too). And I have problems in working with objects in JavaScript.

    The problem:

    [HTML]<a href="JavaScrip t:functionName( object);">Click me</a>[/HTML]
    Somehow it calls toString for the object and rather than it being processed as an object, it is processed as a string.

    Details:
    I'm trying to build a documentation UI (using VBA plugin mztools) and the objects I work with are Project, File, Procedure in that order. The Procedure in turn has arrays of Comments and Parameters.

    [CODE=javascript]function File(Name,Files ) {
    this.Name=Name;
    this.Files=File s
    }
    function File(some arguments....,P rocedures) {
    // The usual this statements...
    }[/CODE]
    Some similar declarations for Procedure, and other objects.
    I'm able to build a library (not sure if the term is correct) of objects where the Projects array is the parent / reference array I keep referring to.
    Now, dynamically, the href of anchors is modified. What I want it to have is:
    JavaScript:func tionName(object )
    But what gets called is:
    JavaScript:func tionName("[object Object]")

    I tried using typeOf within "functionNa me" ...but couldn't figure out what to do with it. Also, I cannot re-construct the object (say Procedure) again from the toString output for it, since there are many more things about it which functionName doesn't know about.

    What should my approach be in such a case ? Thank you in advance for all your inputs.
    Last edited by gits; Dec 27 '07, 07:05 PM. Reason: added code tags
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    hi ...

    welcome to theScripts ....

    i'm not quite sure whether i could follow your explainations on what you really want to do ... but i think you want to create objects from a list of declared ones and create them from their names? something like the following?

    [CODE=javascript]function MY_OBJ() {
    this.foo = 'bar';
    }

    function create_obj(clas s_name) {
    return new Function('retur n new ' + class_name)();
    }

    var a = create_obj('MY_ OBJ');
    [/CODE]
    kind regards

    Comment

    • paragpdoke
      New Member
      • Dec 2007
      • 62

      #3
      Originally posted by gits
      hi ...

      welcome to theScripts ....

      i'm not quite sure whether i could follow your explainations on what you really want to do ... but i think you want to create objects from a list of declared ones and create them from their names? something like the following?

      [CODE=javascript]function MY_OBJ() {
      this.foo = 'bar';
      }

      function create_obj(clas s_name) {
      return new Function('retur n new ' + class_name)();
      }

      var a = create_obj('MY_ OBJ');
      [/CODE]
      kind regards
      Hello Gits.
      Thank you for the welcome note.
      Yes...I have been able to build such objects. Next I create a function / procedure called "display_ob j". This function expects one argument: reference to an object. Thus my function becomes (trying the CODE tags for the first time):
      Code:
      function display_obj(objToDisplay) {
          //Some innerHTML modified here where property "foo" is handled.
      }
      This function is called by clicking on an anchor. So the href for the anchor would be:
      Code:
      JavaScript:display_obj(a);
      But, the browser (Fx and IE) treated "a" as "[Object object]" rather than something that had its own property foo.

      I hope to have clarified the problem this time. Pardon me for lack of ability to put it in a clear manner.

      Comment

      • paragpdoke
        New Member
        • Dec 2007
        • 62

        #4
        Originally posted by paragpdoke
        Hello Gits.
        Thank you for the welcome note.
        Yes...I have been able to build such objects. Next I create a function / procedure called "display_ob j". This function expects one argument: reference to an object. Thus my function becomes (trying the CODE tags for the first time):
        Code:
        function display_obj(objToDisplay) {
            //Some innerHTML modified here where property "foo" is handled.
        }
        This function is called by clicking on an anchor. So the href for the anchor would be:
        Code:
        JavaScript:display_obj(a);
        But, the browser (Fx and IE) treated "a" as "[Object object]" rather than something that had its own property foo.

        I hope to have clarified the problem this time. Pardon me for lack of ability to put it in a clear manner.
        Please give me a few minutes to upload a sample html file.

        Comment

        • paragpdoke
          New Member
          • Dec 2007
          • 62

          #5
          Originally posted by paragpdoke
          Please give me a few minutes to upload a sample html file.
          I have uploaded 3 htm files in attachment: http://paragpdoke.goog lepages.com/Documents.zip
          [Sorry...couldn' t find the upload attachment link on this forum yet. Will try to look for it soon.]

          The 3rd one is exactly the problem I'm running into.

          Comment

          • paragpdoke
            New Member
            • Dec 2007
            • 62

            #6
            Originally posted by paragpdoke
            I have uploaded 3 htm files in attachment: http://paragpdoke.goog lepages.com/Documents.zip
            [Sorry...couldn' t find the upload attachment link on this forum yet. Will try to look for it soon.]

            The 3rd one is exactly the problem I'm running into.
            Sorry for re-post. By 3rd I meant file "HrefModificati on.htm".

            Comment

            • gits
              Recognized Expert Moderator Expert
              • May 2007
              • 5390

              #7
              you want to display the object's codeview? ... so in FF/Moz there is a simple way with the toSource()-method ... or you may use the print_r() function described in this linked howto ...

              kind regards

              Comment

              • acoder
                Recognized Expert MVP
                • Nov 2006
                • 16032

                #8
                Originally posted by paragpdoke
                [Sorry...couldn' t find the upload attachment link on this forum yet. Will try to look for it soon.]
                It's not available when you first post, but if you post and then edit within one hour, you should be able to attach the file.

                Comment

                • paragpdoke
                  New Member
                  • Dec 2007
                  • 62

                  #9
                  Hello Gits.
                  Apologies for a delayed response. I tried the toSource method (after your last reply)...but that too did not work. Here's what the modified file looks like:
                  Code:
                  <html>
                  	<head>
                  		<script language="JavaScript">
                  			function obj(foo) {
                  				this.foo=foo;
                  			}
                  			var a = new obj('thescripts');
                  			function display_obj(objToDisplay) {
                  				document.getElementById('myDiv').innerHTML+=objToDisplay.foo;
                  			}
                  			function change_link() {
                  				document.getElementById('myLink').href="JavaScript:display_obj("+a+");";
                  			}
                  		</script>
                  	</head>
                  	<body>
                  		<a href="JavaScript:change_link();">Click me</a><br>
                  		<a href="JavaScript:display_obj("+a.toSource()+");" id="myLink">My link will change</a><br>
                  		<div id="myDiv"></div>
                  	</body>
                  </html>
                  Unfortunately, I did not understand the intent of the print_r function. Haven't used PHP yet....so it was a little difficult for a newbie to understand.

                  All I'm looking for is a way to make the browser display "thescripts " in the div using JavaScript object "a". When the object is passed statically (not sure if the term is correct - all I mean is without modifying the href via JavaScript) it works. However, when the href is modified by the script, it fails to treat the object as an object.

                  Thank you acoder for the information about attachments. I will remember this when I have to upload something next time.

                  Thanks in advance for any more directions.

                  Comment

                  • gits
                    Recognized Expert Moderator Expert
                    • May 2007
                    • 5390

                    #10
                    hi ...

                    is that what you want? use the onclick instead of the href:

                    [HTML]<html>
                    <head>
                    <script language="JavaS cript">
                    function obj(foo) {
                    this.foo = foo;
                    }

                    var a = new obj('thescripts ');

                    function display_obj(obj ToDisplay) {
                    alert(objToDisp lay.toSource())
                    document.getEle mentById('myDiv ').innerHTML = objToDisplay.fo o;
                    }

                    function change_link() {
                    document.getEle mentById('myLin k').onclick = "display_ob j(" + a + ");";
                    }
                    </script>
                    </head>
                    <body>
                    <a href="#" onclick="change _link();">Click me</a><br>
                    <a href="#" onclick="displa y_obj(a);" id="myLink">My link will change</a><br>
                    <div id="myDiv"></div>
                    </body>
                    </html>
                    [/HTML]
                    kind regards

                    Comment

                    • paragpdoke
                      New Member
                      • Dec 2007
                      • 62

                      #11
                      Originally posted by gits
                      hi ...

                      is that what you want? use the onclick instead of the href:

                      [HTML]<html>
                      <head>
                      <script language="JavaS cript">
                      function obj(foo) {
                      this.foo = foo;
                      }

                      var a = new obj('thescripts ');

                      function display_obj(obj ToDisplay) {
                      alert(objToDisp lay.toSource())
                      document.getEle mentById('myDiv ').innerHTML = objToDisplay.fo o;
                      }

                      function change_link() {
                      document.getEle mentById('myLin k').onclick = "display_ob j(" + a + ");";
                      }
                      </script>
                      </head>
                      <body>
                      <a href="#" onclick="change _link();">Click me</a><br>
                      <a href="#" onclick="displa y_obj(a);" id="myLink">My link will change</a><br>
                      <div id="myDiv"></div>
                      </body>
                      </html>
                      [/HTML]
                      kind regards
                      Hi again Gits.
                      Ummm...no that is not going to help too. See, in the same example you shared above, having:
                      Code:
                      <a href="#" onclick="display_obj(a);" id="myLink">My link will change</a><br>
                      is equivalent of:
                      Code:
                      <a href="JavaScript:display_obj(a);" id="myLink">My link will change</a><br>
                      Both these methods are directly referring to the object "a" directly. Meaning, JavaScript is not modifying either the "href" or the "onclick" attributes of the 2nd anchor in the DOM. Now let us turn to:
                      Code:
                      document.getElementById('myLink').onclick = "display_obj(" + a + ");";
                      or...as in my example:
                      Code:
                      document.getElementById('myLink').href = "display_obj(" + a + ");";
                      Both these lines do not work as I want them to. They somehow fail to treat "a" as an object. My file currently has the following (and does not work):
                      [HTML]
                      <html>
                      <head>
                      <script language="JavaS cript">
                      function obj(foo) {
                      this.foo = foo;
                      }
                      var a = new obj('thescripts ');
                      function display_obj(obj ToDisplay) {
                      alert(objToDisp lay.toSource())
                      document.getEle mentById('myDiv ').innerHTML = objToDisplay.fo o;
                      }
                      function change_link() {
                      document.getEle mentById('myLin k').onclick = "display_ob j(" + a + ");";
                      }
                      </script>
                      </head>
                      <body>
                      <a href="#" onclick="change _link();">Click me</a><br>
                      <a href="#" id="myLink">My onclick will change</a><br>
                      <div id="myDiv"></div>
                      </body>
                      </html>
                      [/HTML]
                      All I want to happen is that JavaScript treats "a" as an object after the "href" or "onclick" have been modified by JavaScript.

                      (I now know the problem with my delayed responses. Even if I've set "Instant email notification" in my control panel, I receive no updates over mail. It is necessary to monitor the thread to learn about replies.)

                      Thanks in advance again,
                      Parag P. Doke

                      Comment

                      • gits
                        Recognized Expert Moderator Expert
                        • May 2007
                        • 5390

                        #12
                        sorry my bad :) ... now have a look ... we must assign a function reference to the onclick-handler ... so it works now. we replace the onclick through calling change_link() ...

                        [CODE=html]<html>
                        <head>
                        <script language="JavaS cript">
                        function obj(foo) {
                        this.foo = foo;
                        }

                        var a = new obj('thescripts ');

                        function display_obj(obj ToDisplay) {
                        alert(objToDisp lay.toSource())
                        document.getEle mentById('myDiv ').innerHTML = objToDisplay.fo o;
                        }

                        function change_link(obj ) {
                        document.getEle mentById('myLin k').onclick = function() {
                        return display_obj(obj );
                        }
                        }
                        </script>
                        </head>
                        <body>
                        <a href="#" onclick="change _link(a);">Clic k me</a><br>
                        <a href="#" onclick="alert( 'test');" id="myLink">My link will change</a><br>
                        <div id="myDiv"></div>
                        </body>
                        </html>
                        [/CODE]
                        kind regards

                        Comment

                        • paragpdoke
                          New Member
                          • Dec 2007
                          • 62

                          #13
                          Originally posted by gits
                          sorry my bad :) ... now have a look ... we must assign a function reference to the onclick-handler ... so it works now. we replace the onclick through calling change_link() ...

                          [CODE=html]<html>
                          <head>
                          <script language="JavaS cript">
                          function obj(foo) {
                          this.foo = foo;
                          }

                          var a = new obj('thescripts ');

                          function display_obj(obj ToDisplay) {
                          alert(objToDisp lay.toSource())
                          document.getEle mentById('myDiv ').innerHTML = objToDisplay.fo o;
                          }

                          function change_link(obj ) {
                          document.getEle mentById('myLin k').onclick = function() {
                          return display_obj(obj );
                          }
                          }
                          </script>
                          </head>
                          <body>
                          <a href="#" onclick="change _link(a);">Clic k me</a><br>
                          <a href="#" onclick="alert( 'test');" id="myLink">My link will change</a><br>
                          <div id="myDiv"></div>
                          </body>
                          </html>
                          [/CODE]
                          kind regards
                          PERFECT ! That is exactly what I wanted to happen.
                          Though I do not understand the significance of each step, I'll try modify this code step by step and learn. Things I learnt from this topic till now:
                          1) "onclick" is better at working with objects rather than "href". (Please correct me if I'm making mistakes.)
                          2) One can skip "JavaScript :" for events as against standard attributes like "href" (shorter code).
                          3) If you accept the name of an object instance as string ("a"), for it to be treated as an object again, one should use a function reference. Somewhere when passing the string to the reference, it gets transformed back into the object.

                          Thank you so much gits for your patience. I'm not even sure if I used the right terms for all these questions :-).

                          Comment

                          • gits
                            Recognized Expert Moderator Expert
                            • May 2007
                            • 5390

                            #14
                            Originally posted by paragpdoke
                            PERFECT ! That is exactly what I wanted to happen.
                            Though I do not understand the significance of each step, I'll try modify this code step by step and learn. Things I learnt from this topic till now:
                            1) "onclick" is better at working with objects rather than "href". (Please correct me if I'm making mistakes.)
                            2) One can skip "JavaScript :" for events as against standard attributes like "href" (shorter code).
                            3) If you accept the name of an object instance as string ("a"), for it to be treated as an object again, one should use a function reference. Somewhere when passing the string to the reference, it gets transformed back into the object.

                            Thank you so much gits for your patience. I'm not even sure if I used the right terms for all these questions :-).
                            no problem ... :) i'm glad to help you ... to you points:

                            1. that's really true :)
                            2. that's really true either :)
                            3. not quite sure what you mean with that. the code above works as follows: we reassign the click-handler and that handler has to be a function-reference so that it is called later on when the event gets fired. now in our special case we have to pass a reference to the object too ... since the handler should access the object. let me give you a short example what a function reference is:

                            [CODE=javascript]var my_func = function(param) {
                            // function code
                            };

                            // as you can see we may assign a variable name to
                            // a function, we could call it with:

                            my_func('foo');

                            // this is equivalent to:

                            function my_func(param) {
                            // function code
                            };

                            // so the name of the function is its reference and we could use
                            // the following for example:

                            window.setTimeo ut(my_func, 1000);

                            // or even - here func_with_param acts as a closure, that means
                            // it is called later on with a param that we store in the function for
                            // later use

                            var func_with_param = function() {
                            return my_func('foo');
                            }

                            window.setTimeo ut(func_with_pa ram, 1000);

                            // this way we avoid the ugly but typical eval-like-usage:

                            window.setTimeo ut('my_func("ba r");', 1000);
                            [/CODE]
                            kind regards

                            Comment

                            Working...