0

I'm trying to make a class that represents a point on a map with coordinates (as of now only in pixels), and an onclick function that displays the name and information about the location on the map, but I keep getting "undefined" as a value, and I feel like I'm missing something basic and it's driving me crazy. This is the code:

function Point (X, Y, N)
{
this.LX = X;
this.LY = Y;
this.name = N;

var pommap = document.getElementById("map");
var divic = document.createElement("div");

divic.style.position = "absolute";
divic.style.border = "2px solid black";
divic.style.height = "20px";
divic.style.width = "20px";
divic.style.top = X + "px";
divic.style.left = Y + "px";

divic.onclick = function()
{
    var disp = document.createElement("div");
    disp.style.position = "absolute";
    disp.style.border = "1px dashed black";
    disp.style.width = "200px";
    disp.style.height = "100px";
    disp.style.left = "1100px";
    disp.style.top = "200px";
    disp.innerHTML = this.name;

    var pmap = document.getElementById("map");
    pmap.appendChild(disp);
}

pommap.appendChild(divic);

}

The onclick function works, and my DIV gets drawn and appended correctly, but the only value inside is "undefined" string instead of the name I intended. This part I reckon is to blame, and I have no idea why:

disp.innerHTML = this.name;
  • because the value of `this` is being overridden by the calling context of `onclick`. You can bind it like so: `divic.onclick = function() { ... }.bind(this)` – Hamms Jun 15 '16 at 00:36

1 Answers1

0

Note this snippet. this in javascript onclick handler is actually the dom element that just got clicked. Not an instance of your parent object the handler is a part of.

Problem

var btn = document.getElementById('foo');
btn.name = 'My Button';

btn.onclick = function() {
  bar.innerHTML = this.name;
}
<button id="foo">Test</button>

<div id="bar"></div>

Solution

Cache off this, and reference that within your object.

var parent = document.getElementById('bar');

function Obj(name) {
  this.name = name;

  // Cache off internal `self` variable, equal to this instance.
  var self = this;

  function createDomElement_WRONG() {
    var element = document.createElement('div');
    // Note the incorrect usage of `this` here.
    element.innerHTML = this.name;
    parent.appendChild(element);
  }

  function createDomElement_RIGHT() {
    var element = document.createElement('div');
    // Use `self` instead of `this`.
    element.innerHTML = self.name;
    parent.appendChild(element);
  }

  createDomElement_WRONG();
  createDomElement_RIGHT();
}

var foo = new Obj('foo');
var bar = new Obj('bar');
<div id="bar"></div>
mariocatch
  • 8,305
  • 8
  • 50
  • 71