0

If I have a movieClip on the root timeline with the instance name of box. Inside the MC I have a colored square shape and the following code:

myNum = 5;

EDIT: In desparate act to get any response I have also on the line below:

var myNum = 3;

just to cover all my bases, but still no output response of either value END OF EDIT.

On the root timeline I have :

this.box.addEventListener("click", clickHandler);

function clickHandler(e) {
    console.log(e.currentTarget.myNum);
}

this returns undefined. How do I access myNum?

Michael
  • 119
  • 1
  • 13
  • is myNum a global variable? – Jose CC Jan 19 '18 at 15:27
  • it should be local as in the end I'll have multiple MC's but with different values. When testing I did both 'var myNum = 5' & 'myNum = 3', yet I got 'undefined' as returned output – Michael Jan 19 '18 at 15:28
  • that is because currentTarget is not an object and if it was you didn't assign myNum to the object.........https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget – Jose CC Jan 19 '18 at 15:35

2 Answers2

0

please let me know if this is suitable for what you are trying to accomplish.

<button id="elem" data-mynum="3"> hello</button>

var elem = document.getElementById('elem');
elem.addEventListener("click", clickHandler);

function clickHandler(e) {
    console.log(e.currentTarget.dataset.mynum);
}

we just assign a data attribute to the node so that way you can access whatever data you want to attach to the element

Jose CC
  • 865
  • 11
  • 24
  • I can't see how that would translate into the structure I have. I guess what I am looking for is the equivalent of '.dataset.' in your clickHandler but I don't know ~what~ that is for my structure. – Michael Jan 19 '18 at 15:50
0

To access a variable inside of an object, the variable has to be a property (key) on the object. myNum isn't a property of e.currentTarget and just declaring a variable doesn't give any random object the property... you have to set the property on the object, like this:

this.box.myNum = 3;
this.box.addEventListener('click', clickHander);
...

Although as Jose CC's answer mentions, putting custom attributes on elements is not standard (though it will work) and the way it should be done is with a data- attribute.

var box = document.getElementById('box');
box.dataset.myNum = 3;
box.addEventListener('click', clickHandler);

function clickHandler(e) {
  console.log(e.currentTarget.dataset.myNum);
}
<div id="box">My box</div>
skyline3000
  • 7,639
  • 2
  • 24
  • 33