DOM dynamically built table and addEventListener....

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Quarco

    DOM dynamically built table and addEventListener....

    This one is driving me nuts....



    var tbl = document.create Element("table" );
    var tbody = document.create Element("tbody" );

    for(var i=0; i<10; i++) {
    var row = document.create Element("tr");
    var curVAR = someCurrentValu eOfArray[i];

    row.addEventLis tener('click', function(e) {
    alert(curVAR);
    }, false);

    var cell = document.create Element("td");
    var cellText = document.create TextNode(i);
    cell.appendChil d(cellText); row.appendChild (cell);

    tbody.appendChi ld(row);
    }
    tbl.appendChild (tbody);
    document.getEle mentById('tdiv' ).appendChild(t bl);

    ====

    Now... Why isn't the curVAR 'assigned' to the row-alert-function???.
    if I click one of the rows, only the last curVAR (10) is alerted, but the
    i-variable is nicely showed 0 to 9 in the row....

    Anyone???

    Thanx in advance...


  • Joost Diepenmaat

    #2
    Re: DOM dynamically built table and addEventListene r....

    "Quarco" <dont@bother.it writes:
    This one is driving me nuts....
    >
    >
    >
    var tbl = document.create Element("table" );
    var tbody = document.create Element("tbody" );
    >
    for(var i=0; i<10; i++) {
    var row = document.create Element("tr");
    var curVAR = someCurrentValu eOfArray[i];
    >
    row.addEventLis tener('click', function(e) {
    alert(curVAR);
    }, false);
    >
    var cell = document.create Element("td");
    var cellText = document.create TextNode(i);
    cell.appendChil d(cellText); row.appendChild (cell);
    >
    tbody.appendChi ld(row);
    }
    tbl.appendChild (tbody);
    document.getEle mentById('tdiv' ).appendChild(t bl);
    >
    ====
    >
    Now... Why isn't the curVAR 'assigned' to the row-alert-function???.
    if I click one of the rows, only the last curVAR (10) is alerted, but the
    i-variable is nicely showed 0 to 9 in the row....
    >
    Anyone???
    The i and curVar variables are re-assigned in the loop (javascript
    does not have block scope, only function scope), so all your event
    handlers are closing over the same curVar variable, which will have
    someCurrentEtc[9] as its value at the end of the loop.

    You need to create a new variable to close over, by creating a new
    scope:

    (function(curVa r) { // or make a named function and call that
    row.addEventLis tener('click', function(e) {
    alert(curVAR);
    }, false);
    })(curVar);


    --
    Joost Diepenmaat | blog: http://joost.zeekat.nl/ | work: http://zeekat.nl/

    Comment

    • Jorge

      #3
      Re: DOM dynamically built table and addEventListene r....

      Quarco wrote:
      >
      Now... Why isn't the curVAR 'assigned' to the row-alert-function???.
      if I click one of the rows, only the last curVAR (10) is alerted, but the
      i-variable is nicely showed 0 to 9 in the row....
      You could save curVar as a property of the element ( td / tr ) :

      <html><head><sc ript>
      window.onload= function () {
      var d= document,
      anArray= ['a0','b1','c2', 'd3','e4','f5', 'g6','h7','i8', 'j9'],
      y= function (p) { return d.createElement (p) },
      tbody= y("tbody"),
      i, cell;

      for(i= 0; i< 10; i++) {
      (tbody.appendCh ild(y('tr'))).a ppendChild(cell = y("td"));
      cell.innerHTML= i;
      cell.curVAR= anArray[i];
      cell.addEventLi stener('click', function(e) { alert(this.curV AR) },
      false);
      }

      (d.getElementBy Id('tdiv').appe ndChild(y("tabl e"))).appendChi ld(tbody);
      };
      </script></head><body><div id="tdiv"></div></body></html>

      --Jorge.

      Comment

      • Thomas 'PointedEars' Lahn

        #4
        Re: DOM dynamically built table and addEventListene r....

        Jorge wrote:
        Quarco wrote:
        >Now... Why isn't the curVAR 'assigned' to the row-alert-function???.
        >if I click one of the rows, only the last curVAR (10) is alerted, but the
        >i-variable is nicely showed 0 to 9 in the row....
        >
        You could save curVar as a property of the element ( td / tr ) :
        Recommended against because that would mean augmenting a host object which
        is error-prone. Search the archives.


        PointedEars
        --
        realism: HTML 4.01 Strict
        evangelism: XHTML 1.0 Strict
        madness: XHTML 1.1 as application/xhtml+xml
        -- Bjoern Hoehrmann

        Comment

        • Quarco

          #5
          Re: DOM dynamically built table and addEventListene r....

          Taking a bow...
          Thank you Joost...!!!


          :-)


          "Joost Diepenmaat" <joost@zeekat.n lschreef in bericht
          news:878wxnsxhx .fsf@zeekat.nl. ..
          "Quarco" <dont@bother.it writes:
          >
          >This one is driving me nuts....
          >>
          >>
          >>
          > var tbl = document.create Element("table" );
          > var tbody = document.create Element("tbody" );
          >>
          > for(var i=0; i<10; i++) {
          > var row = document.create Element("tr");
          > var curVAR = someCurrentValu eOfArray[i];
          >>
          > row.addEventLis tener('click', function(e) {
          > alert(curVAR);
          > }, false);
          >>
          > var cell = document.create Element("td");
          > var cellText = document.create TextNode(i);
          > cell.appendChil d(cellText); row.appendChild (cell);
          >>
          > tbody.appendChi ld(row);
          > }
          > tbl.appendChild (tbody);
          > document.getEle mentById('tdiv' ).appendChild(t bl);
          >>
          >====
          >>
          >Now... Why isn't the curVAR 'assigned' to the row-alert-function???.
          >if I click one of the rows, only the last curVAR (10) is alerted, but the
          >i-variable is nicely showed 0 to 9 in the row....
          >>
          >Anyone???
          >
          The i and curVar variables are re-assigned in the loop (javascript
          does not have block scope, only function scope), so all your event
          handlers are closing over the same curVar variable, which will have
          someCurrentEtc[9] as its value at the end of the loop.
          >
          You need to create a new variable to close over, by creating a new
          scope:
          >
          (function(curVa r) { // or make a named function and call that
          row.addEventLis tener('click', function(e) {
          alert(curVAR);
          }, false);
          })(curVar);
          >
          >
          --
          Joost Diepenmaat | blog: http://joost.zeekat.nl/ | work: http://zeekat.nl/

          Comment

          • Jorge

            #6
            Re: DOM dynamically built table and addEventListene r....

            On Jun 2, 8:21 pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
            wrote:
            Recommended against because that would mean augmenting a host object which
            is error-prone.  Search the archives.
            >
            I didn't know, and I do it all the time !
            Would you please tell me why, in a few words ?
            Is it a problem, specifically, of a certain browser ?
            (I'll look into the archives as well, I promise)

            Thanks,
            --Jorge.

            Comment

            • Jorge

              #7
              Re: DOM dynamically built table and addEventListene r....

              On Jun 2, 8:21 pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
              wrote:
              You could save curVar as a property of the element ( td / tr ) :
              >
              Recommended against because that would mean augmenting a host object which
              is error-prone.  Search the archives.
              I didn't know, and I do it all the time !
              Would you tell me why is it bad, in a few words ?
              (I'll look into the archive as well, I promise)

              Thanks,
              --Jorge.

              Comment

              • Thomas 'PointedEars' Lahn

                #8
                Re: DOM dynamically built table and addEventListene r....

                Jorge wrote:
                Thomas 'PointedEars' Lahn wrote:
                >Recommended against because that would mean augmenting a host object which
                >is error-prone. Search the archives.
                >
                I didn't know, and I do it all the time !
                Tough luck.
                Would you please tell me why, in a few words ?
                In contrast to native objects, host objects do not need to support
                augmentation. See the ECMAScript Language Specification, Edition 3 Final,
                subsection "8.6.2 Internal Properties and Methods".
                Is it a problem,
                Yes.
                specifically, of a certain browser ?
                No, it can cause your Web application to break. Silently, or with an error
                message. Anywhere, anytime.
                (I'll look into the archives as well, I promise)
                Good.


                HTH

                PointedEars
                --
                Anyone who slaps a 'this page is best viewed with Browser X' label on
                a Web page appears to be yearning for the bad old days, before the Web,
                when you had very little chance of reading a document written on another
                computer, another word processor, or another network. -- Tim Berners-Lee

                Comment

                • Jorge

                  #9
                  Re: DOM dynamically built table and addEventListene r....

                  On Jun 2, 9:53 pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
                  wrote:
                  Jorge wrote:
                  Thomas 'PointedEars' Lahn wrote:
                  Recommended against because that would mean augmenting a host object which
                  is error-prone.  Search the archives.
                  >
                  I didn't know, and I do it all the time !
                  >
                  Tough luck.
                  >
                  Would you please tell me why, in a few words ?
                  >
                  In contrast to native objects, host objects do not need to support
                  augmentation.  See the ECMAScript Language Specification, Edition 3 Final,
                  subsection "8.6.2 Internal Properties and Methods".
                  >
                  Is it a problem,
                  >
                  Yes.
                  >
                  specifically, of a certain browser ?
                  >
                  No, it can cause your Web application to break.  Silently, or with an error
                  message.  Anywhere, anytime.
                  >
                  But, for example :

                  var y= function (p) { return document.create Element(p) },
                  e= y('tag');

                  e.property= "whatever";

                  Is e a "host object" ?

                  Or you mean :

                  (y('tag')).prop erty= "whatever";

                  ??

                  --Jorge.

                  Comment

                  • Thomas 'PointedEars' Lahn

                    #10
                    Re: DOM dynamically built table and addEventListene r....

                    Jorge wrote:
                    Thomas 'PointedEars' Lahn wrote:
                    >[Trying to augment host objects] can cause your Web application to
                    >break. Silently, or with an error message. Anywhere, anytime.
                    >
                    But, for example :
                    >
                    var y= function (p) { return document.create Element(p) },
                    This as it is does not make much sense. See our recent discussion about the
                    viability of Prototype.js's $() method.
                    e= y('tag');
                    >
                    e.property= "whatever";
                    >
                    Is e a "host object" ?
                    `e' is *a reference to* a host object then (probably an object that
                    implements an element-related interface of W3C DOM Level 2 HTML).

                    In ECMAScript implementations , you can only work with references to objects,
                    never with objects directly.
                    Or you mean :
                    >
                    (y('tag')).prop erty= "whatever";
                    >
                    ??
                    You could also write

                    y('tag').proper ty = "whatever";

                    or

                    [{foo: y('tag')}][0]["foo"].property = "whatever";

                    and so on with the same (here: possibly disastrous) outcome. How you
                    construct the reference to an object makes no difference regarding the
                    kind of object you are referring to.

                    However, your second variant adds further error-proneness as y() may not
                    return an object reference or a primitive value convertible to an object in
                    which case the property lookup would then result in a TypeError (exception).

                    With the first variant you can at least do feature-testing on the return
                    value and perhaps also on the property before you attempt to assign to the
                    property of the object; that would generally seem to be a wise course of
                    action, with the exception of universally supported properties of native
                    objects.


                    Please trim your quotes.


                    PointedEars
                    --
                    Prototype.js was written by people who don't know javascript for people
                    who don't know javascript. People who don't know javascript are not
                    the best source of advice on designing systems that use javascript.
                    -- Richard Cornford, cljs, <f806at$ail$1$8 300dec7@news.de mon.co.uk>

                    Comment

                    • Jorge

                      #11
                      Re: DOM dynamically built table and addEventListene r....

                      On Jun 2, 11:26 pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
                      wrote:
                      In contrast to native objects, host objects do not need to support
                      augmentation. See the ECMAScript Language Specification, Edition 3 Final,
                      subsection "8.6.2 Internal Properties and Methods".
                      "Every object (including host objects) must implement the
                      [[Prototype]]
                      and [[Class]] properties and the [[Get]], [[Put]], [[CanPut]],
                      [[HasProperty]], [[Delete]], and [[DefaultValue]] methods."

                      "Host objects may implement these methods in any manner unless
                      specified
                      otherwise; for example, one possibility is that [[Get]] and [[Put]]
                      for
                      a particular host object indeed fetch and store property values but
                      [[HasProperty]] always generates false."

                      Well, this is what I understand :

                      1- Host objects must implement the Get and Put (and others) methods.
                      2- The way they implement these methods is not specified ("any
                      manner").

                      I hope that "implement in any manner" doesn't mean that a get method
                      might not fetch a property's value, nor that a put method might
                      not store it...

                      It's just that the manner in which they *do it* might be "any
                      manner".

                      And as long as a property can be read/written, does it matter in what
                      "manner" it's done ?

                      Or the problem is with any of the other methods, not with get/put ?
                      [Trying to augment host objects] can cause your Web application to
                      break.  Silently, or with an error message.  Anywhere, anytime.
                      Is it a certain browser that has these problems ?
                      (I really don't care about JS/ES outside of a browser).
                      How you
                      construct the reference to an object makes no difference regarding the
                      kind of object you are referring to.
                      You're right, I thought about it and got it (just after hitting
                      google's
                      'post' button, and before reading your post). Thanks for having the
                      patience to answer so well and politely.
                      Please trim your quotes.
                      (trimmed)

                      Thanks,
                      --Jorge.

                      Comment

                      • Thomas 'PointedEars' Lahn

                        #12
                        Re: DOM dynamically built table and addEventListene r....

                        Jorge wrote:
                        Thomas 'PointedEars' Lahn wrote:
                        >In contrast to native objects, host objects do not need to support
                        >augmentation . See the ECMAScript Language Specification, Edition 3
                        >Final, subsection "8.6.2 Internal Properties and Methods".
                        >
                        "Every object (including host objects) must implement the [[Prototype]]
                        and [[Class]] properties and the [[Get]], [[Put]], [[CanPut]],
                        [[HasProperty]], [[Delete]], and [[DefaultValue]] methods."
                        >
                        "Host objects may implement these methods in any manner unless specified
                        otherwise; for example, one possibility is that [[Get]] and [[Put]] for a
                        particular host object indeed fetch and store property values but
                        [[HasProperty]] always generates false."
                        >
                        Well, this is what I understand :
                        >
                        1- Host objects must implement the Get and Put (and others) methods.
                        2- The way they implement these methods is not specified ("any manner").
                        >
                        I hope that "implement in any manner" doesn't mean that a get method
                        might not fetch a property's value, nor that a put method might not store
                        it...
                        But that is exactly what it means.
                        It's just that the manner in which they *do it* might be "any manner".
                        No.
                        And as long as a property can be read/written, does it matter in what
                        "manner" it's done ?
                        No, the "manner" may also include throwing a runtime exception. See below.
                        Or the problem is with any of the other methods, not with get/put ?
                        [[Get]] and [[Put]] are of primary concern as they are used in quite a
                        number of ECMAScript algorithms, particularly in those for property
                        accessors and assignments.
                        >>>[Trying to augment host objects] can cause your Web application to
                        >>>break. Silently, or with an error message. Anywhere, anytime.
                        >
                        Is it a certain browser that has these problems ?
                        This is obviously impossible to say until you have tested all properties in
                        all known past and current browsers with all possible values. And it does
                        not mean anything for future versions or browsers you do not know of yet.

                        It is known of the MSHTML DOM that a host object in the scope chain prevents
                        the modification of its properties ([[Put]]) that are references to host
                        objects themselves (element objects for named or ID'd elements), and that
                        certain properties cause a runtime error on read access ([[Get]]). This is
                        proof that implementations do follow the specification in that regard.

                        Or consider the object referred to by the `style' property of element
                        objects in HTML DOMs. It has certain standardized and proprietary shortcut
                        properties for assigning CSS property values. If you assign a value to such
                        a property ([[Put]]) and that value is not valid for that property, you will
                        observe that the property does not have the assigned value but the original
                        value in several implementations .

                        Since such proof exists, it would appear to be unwise to run the risk of
                        breaking your script with trying to augment host objects.
                        (I really don't care about JS/ES outside of a browser).
                        However, Web browsers are only a subset of scriptable user agents.
                        >How you construct the reference to an object makes no difference
                        >regarding the kind of object you are referring to.
                        >
                        You're right, I thought about it and got it (just after hitting google's
                        'post' button, and before reading your post). Thanks for having the
                        patience to answer so well and politely.
                        You are welcome.


                        PointedEars
                        --
                        realism: HTML 4.01 Strict
                        evangelism: XHTML 1.0 Strict
                        madness: XHTML 1.1 as application/xhtml+xml
                        -- Bjoern Hoehrmann

                        Comment

                        • Jorge

                          #13
                          Re: DOM dynamically built table and addEventListene r....

                          I hope that "implement in any manner" doesn't mean that a get method
                          might not fetch a property's value, nor that a put method might not store
                          it...
                          >
                          But that is exactly what it means.
                          BTW, I found this article that you were interested in:
                          <news:483F3F79. 8080605@Pointed Ears.de>.
                          There's at least one other: <news:4836A152. 2090609@Pointed Ears.de>
                          Still, I can't figure out why, if this is so crude, I have never had a
                          problem with it.
                          Might it be because I never program for nor test in IEs ?
                          If the property can be set and can be read, why isn't it safe to go on
                          with it ?

                          Is there any doc online, in the browser's libraries, or anywhere, that
                          says clearly "don't do this", and why not ?
                          (in w3c, Mozilla, MS, Opera, Webkit...)

                          TIA,
                          --Jorge.

                          Comment

                          • Thomas 'PointedEars' Lahn

                            #14
                            Re: DOM dynamically built table and addEventListene r....

                            Jorge wrote:
                            >>I hope that "implement in any manner" doesn't mean that a get method
                            >>might not fetch a property's value, nor that a put method might not store
                            >>it...
                            >But that is exactly what it means.
                            >
                            >BTW, I found this article that you were interested in:
                            ><news:483F3F79 .8080605@Pointe dEars.de>.
                            >There's at least one other: <news:4836A152. 2090609@Pointed Ears.de>
                            >
                            Still, I can't figure out why, if this is so crude, I have never had a
                            problem with it.
                            You got away jumping a red light 999 times now.
                            Might it be because I never program for nor test in IEs ?
                            No.
                            If the property can be set and can be read,
                            If. I have showed that there are cases where this is not possible.
                            why isn't it safe to go on with it ?
                            You cannot know which execution environment your code is exposed to during
                            its life cycle.
                            Is there any doc online, in the browser's libraries, or anywhere, that
                            says clearly "don't do this", and why not ?
                            I have pointed you to the language specification already.
                            (in w3c, Mozilla, MS, Opera, Webkit...)
                            This is a feature that can be expected with conforming language
                            implementations . I wonder what is so difficult to understand about that.


                            PointedEars

                            Comment

                            • VK

                              #15
                              Re: DOM dynamically built table and addEventListene r....

                              On Jun 3, 4:52 pm, Jorge <jo...@jorgecha morro.comwrote:
                              I hope that "implement in any manner" doesn't mean that a get method
                              might not fetch a property's value, nor that a put method might not store
                              it...
                              >
                              But that is exactly what it means.
                              BTW, I found this article that you were interested in:
                              <news:483F3F79. 8080605@Pointed Ears.de>.
                              There's at least one other: <news:4836A152. 2090609@Pointed Ears.de>
                              >
                              Still, I can't figure out why, if this is so crude, I have never had a
                              problem with it.
                              Might it be because I never program for nor test in IEs ?
                              If the property can be set and can be read, why isn't it safe to go on
                              with it ?
                              I would disregard whatever Thomas is saying unless it is a request for
                              a particular standard reference where he is pretty good. By having no
                              practical programming experience, he has made a credo of the type "it
                              doesn't fail in any place anyone knows about, but it may fail in some
                              place no one knows about". This gives him an opportunity for the
                              endless and useless pedantic rambling which is IMHO the only reason
                              he's posting here. For a recent sample he does believe or pretending
                              to believe that any script using window.onload is error prone and the
                              only safe alternative is using <body onload=... Sapienti sat.

                              For the possibility of DOM object augmentation failure you may account
                              expando flag state for IE. See
                              Expando properties are properties added to DOM nodes with JavaScript, where those properties are not part of the object's DOM specification:


                              I never in my life saw yet this flag being used by anyone nor I even
                              know if it still does work, but if we decided to explore the most low
                              probable yet at least possible situations then here my two bucks.

                              Comment

                              Working...