AddEventListener and `this` do not work properly

I am an experienced programmer, but somewhat new to web programming. I am trying to learn Javascript, HTML5 and SVG using VS2010 by writing an HTML page that plays Tic-Tac-Toe with Javascript.

I successfully create each of the nine squares as SVG elements <rect...>, however I am having problems with the click event handlers for each square.

Here are the basic SVG elements that exist in the HTML file:

  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
    id="svgTTT" width="150" height="150" viewBox="0 0 300 300"  >
    <rect width="3" height="300" x="99" fill="#008d46" />
    <rect width="3" height="300" x="199" fill="#000000" />
    <rect width="300" height="3" y="99" fill="#008d46" />
    <rect width="300" height="3" y="199" fill="#d2232c" />
  </svg>

These static elements are <rect>drawn for the cross-hash strings of the TicTacToe board. Nine squares of the panel are created in the javascript function called from the Windows boot event (below).

Here's the javascript (in-line in the element <script>in the body of the HTML):

<script type="text/javascript">
  function getEl(s) { return document.getElementById(s); }

  var svg;  // get the TTT svg

  // execute after HTML has rendered
  window.onload = function () {
    svg = getEl("svgTTT");
    tttSetupSquares(svg);
    alert("click-squares are setup.");
  }

  var cells = new Array(3);
  // setup the click squares
  function tttSetupSquares(brd) {
    for (var i = 0; i < 3; i++) {
      cells[i] = new Array(3);
      for (var j = 0; j < 3; j++) {
        var x = 3 + (i * 100);
        var y = 3 + (j * 100);
        var newId = "svgTTTsqr" + i.toString() + j.toString();
        // add in new rect with html
        brd.innerHTML += "<rect id='"+newId+"' width='93' height='93' "
                        + "fill='#00DD00' x='" + x.toString() + "' y ='" + y.toString() + "'"
                        + " />";
        //find it using the newId
        var rect = document.getElementById(newId);
        //make a cell object to contain all of this
        var cell = {
          col: i,
          row: j,
          pSvg: svg,
          rect: rect,

          handleClick: function (event) {
            try {
              // this line fails because `this` is the target, not the cell
              var svgNS = this.pSvg.namespaceURI;

              var line = document.createElementNS(svgNS, 'line');
              this.pSvg.appendChild(line);
            }
            catch (err) {
              alert("handlClick err: " + err);
            }
          }
        }

        //add a click handler for the rect/cell
        cell.rect.addEventListener("click", cell.handleClick, false);
        //(only seems to work the last time it is executed)

        //save the cell object for later use
        cells[i][j] = cell;
      }
    }
  }
</script>

( , HTML, .)

:

  • , addEventListener. . (svgTTTsqr22) cell.handleClick, 2 (). Chrome (F12) <rect>, , .

  • cell.handleClick, (var svgNS = this.pSvg.namespaceURI;) "undefined", "namespaceURI". " Devleoper Tools" , , this cell, SVG <rect>, .

, :

. ,

. ?

+4
3

1.

innerHTML DOM HTML. , DOM HTML. , innerHTML, , DOM. - , <rect> s:

// Use DOM manipulation instead of innerHTML
var rect = document.createElementNS(svg.namespaceURI, 'rect');
rect.setAttributeNS(null, "id", newId);
rect.setAttributeNS(null, "fill", "#00DD00");
rect.setAttributeNS(null, "width", "93");
rect.setAttributeNS(null, "height", "93");
rect.setAttributeNS(null, "x", x);
rect.setAttributeNS(null, "y", y);
svg.appendChild(rect);

2. this

, this, , . this, brd, .tttSetupSquares().

handleClick: function (event) {
    try {
        var svgNS = brd.namespaceURI;
        var line = document.createElementNS(svgNS, 'line');
        brd.appendChild(line);
    }
    catch (err) {
        alert("handlClick err: " + err);
    }
}

. :

function getEl(s) { return document.getElementById(s); }

  var svg;  // get the TTT svg
  var cells = new Array(3);

  // execute after HTML has rendered
  !(function () {
    svg = getEl("svgTTT");
    tttSetupSquares(svg);
    alert("click-squares are setup.");
  }());

  // setup the click squares
  function tttSetupSquares(brd) {
    for (var i = 0; i < 3; i++) {
      cells[i] = new Array(3);
      for (var j = 0; j < 3; j++) {
        var x = 3 + (i * 100);
        var y = 3 + (j * 100);
        var newId = "svgTTTsqr" + i.toString() + j.toString();
        
        // Use DOM manipulation instead of innerHTML
		var rect = document.createElementNS(svg.namespaceURI, 'rect');
        rect.setAttributeNS(null, "id", newId);
        rect.setAttributeNS(null, "fill", "#00DD00");
        rect.setAttributeNS(null, "width", "93");
        rect.setAttributeNS(null, "height", "93");
        rect.setAttributeNS(null, "x", x);
        rect.setAttributeNS(null, "y", y);
        svg.appendChild(rect);
        
        //make a cell object to contain all of this
        var cell = {
          col: i,
          row: j,
          pSvg: brd,
          rect: rect,

          handleClick: function (event) {
            try {
              //console.log(this);
              var svgNS = brd.namespaceURI;
              var line = document.createElementNS(svgNS, 'line');
              line.setAttributeNS(null, "x1", this.x.baseVal.value);
              line.setAttributeNS(null, "y1", this.y.baseVal.value);
              line.setAttributeNS(null, "x2", this.x.baseVal.value + this.width.baseVal.value);
              line.setAttributeNS(null, "y2", this.y.baseVal.value + this.height.baseVal.value);
              brd.appendChild(line);
            }
            catch (err) {
              alert("handlClick err: " + err);
            }
          }
        }

        //add a click handler for the rect/cell
        cell.rect.addEventListener("click", cell.handleClick, false);

        //save the cell object for later use
        cells[i][j] = cell;
      }
    }
  }
line {
  stroke: red;
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
    id="svgTTT" width="150" height="150" viewBox="0 0 300 300"  >
    <rect width="3" height="300" x="99" fill="#008d46" />
    <rect width="3" height="300" x="199" fill="#000000" />
    <rect width="300" height="3" y="99" fill="#008d46" />
    <rect width="300" height="3" y="199" fill="#d2232c" />
  </svg>
Hide result
+4

, "this" , , , . . self=this .bind(). , . :
var self = this?
: javascript
: http://ryanmorr.com/understanding-scope-and-context-in-javascript/
: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/this

. "this". EventListener. , . . : .handleEvent. addEventListener(), . , "this" . . , , .handleEvent - .

:

  function getEl(s) { return document.getElementById(s); }

  var svg;  // get the TTT svg

  // execute after HTML has rendered
  window.onload = function () {
    svg = getEl("svgTTT");
    tttSetupSquares(svg);
    //alert("click-squares are setup.");
  }

  var cells = new Array(3);
  // setup the click squares
  function tttSetupSquares(brd) {
    for (var i = 0; i < 3; i++) {
      cells[i] = new Array(3);
      for (var j = 0; j < 3; j++) {
        var x = 3 + (i * 100);
        var y = 3 + (j * 100);
        var rect= document.createElementNS("http://www.w3.org/2000/svg","rect")
rect.setAttribute("x",x);
rect.setAttribute("y",y);
rect.setAttribute("width",100);
rect.setAttribute("height",100);
rect.setAttribute("fill","grey")

        brd.appendChild(rect)
        var cell = {
          col: i,
          row: j,
          pSvg: svg,
          rect: rect,

          handleEvent: function (event) {
            try {
              // this line fails because `this` is the target, not the cell
              var svgNS = this.pSvg.namespaceURI;

              var line = document.createElementNS(svgNS, 'line');
              line.setAttribute("x1",this.rect.getAttribute("x"))
              line.setAttribute("y1",this.rect.getAttribute("y"))
              line.setAttribute("x2",this.rect.getAttribute("x")*1+this.rect.getAttribute("width")*1)
              line.setAttribute("y2",this.rect.getAttribute("y")*1+this.rect.getAttribute("height")*1)
              line.setAttribute("stroke","red")
              this.pSvg.appendChild(line);
              document.getElementById("out").innerHTML="rect("+this.col+","+this.row+") was clicked"
            }
            catch (err) {
              alert("handlClick err: " + err);
            }
          }
        }

        //add a click handler for the rect/cell
        cell.rect.addEventListener("click", cell, false);
        //(only seems to work the last time it is executed)

        //save the cell object for later use
        cells[i][j] = cell;
      }
    }
  }
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
    id="svgTTT" width="150" height="150" viewBox="0 0 300 300"  >
    <rect width="3" height="300" x="99" fill="#008d46" />
    <rect width="3" height="300" x="199" fill="#000000" />
    <rect width="300" height="3" y="99" fill="#008d46" />
    <rect width="300" height="3" y="199" fill="#d2232c" />
  </svg>

<div id="out"></div>
Hide result

EventHandlers, , - !

+3

:

. , jQuery Angular React, . DOM . "click" wrapping event.target, , .

svg.addEventListener("click", function (e) {
    if (e.target.nodeName === "rect" && (/^svgTTTsqr/).test(e.target.id)) {
        // Use a regexp on  e.target.id to find your
        // cell object in `cells`
    }
});

, , , .

// Generating the HTML
brd.innerHTML += "<rect id='"+newId+"' data-i='" + i + "' data-j='" + j + "' "

// The event handler:
svg.addEventListener("click", function (e) {
    if (e.target.nodeName === "rect" && (/^svgTTTsqr/).test(e.target.id)) {
        var i = e.target.getAttribute("data-i");
        var j = e.target.getAttribute("data-j");
        var cell = cells[i][j];
        cell.handleClick();
    }
});

, , HTML, DOM , HTML DOM .

,

1) , :( , . , , .

2) , , 'this' , . , 'this'. , , 'this' , . function () {}.bind(cell), , , this ​​ cell, , , bind.

+2
source

Source: https://habr.com/ru/post/1609120/


All Articles