0

In javascript I can do this:

var mydata = {foo:"bar"};
element.addEventListener("click", myFunc);

function myFunc(e) {
    // need to get {foo:"bar"}
}

I want to access the mydata variable from the myFunc function, but passed as parameter data, whenever the click event happens in the element. I don't want to get it through some global variable. I want to get that data passed in somehow. Something like this, if it existed:

var mydata = {foo:"bar"};
element.addEventListener("click", mydata, myFunc);

function myFunc(e) {
    var mydata = e.data;
}

Does anyone know a way? And no, you can't use jquery or any plugins.

Thanks

omega
  • 40,311
  • 81
  • 251
  • 474

2 Answers2

0

You can't pass it directly. But below idea should work

element.addEventListener('click', myFunc);
element.mData = mydata;
function myFunc(e)
{
  console.log( e.target.mData );
}
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

You can add an anonymous function on the event listener method. And also add the data as an element property.

element.mydata = {foo:"bar"};
element.addEventListener("click", function(){ myFunc(this.mydata); });

Hence

function myFunc(e){
  console.log(e.foo); //outputs "bar";
}
Abana Clara
  • 4,602
  • 3
  • 18
  • 31