Note that there are some explanatory texts on larger screens.

plurals
  1. POjavascript - passing additional parameters into an event handler
    text
    copied!<p>I have a javascript object which has some defined variables and attaches some event handlers. I'd like the event handlers to have access to the defined variables. Is there a way to do that ? The event-handlers are within their own local scope so don't have access to the object variables. Is there a way to pass them in without using global variables ? </p> <p>I have an idea that closures would solves this but I'm not sure how. </p> <p>the code below will print the object name when the page loads but when you click on the map dom object it will say name is undefined.</p> <p>All help much appreciated.</p> <p>Colm</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;Map Test&lt;/title&gt; &lt;meta charset="utf-8" /&gt; &lt;script type="text/javascript"&gt; window.onload = function() { var e = new EvtTest(); e.printName(); e.attachEvents(); }; function EvtTest() { this.name = "EvtTest"; } EvtTest.prototype.name = null; EvtTest.prototype.attachEvents = function () { var map = document.getElementById("map"); map.addEventListener ('click', this.evtHandler, false); }; EvtTest.prototype.printName = function () { console.log ("This Name : " + this.name); }; EvtTest.prototype.evtHandler = function (e) { e.preventDefault(); console.log ("Name : " + this.name); }; &lt;/script&gt; &lt;style type="text/css"&gt; html, body { height:100%; width:100%; margin: 0; background-color:red; } #map { height: 300px; width: 300px; background-color:yellow; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="map"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload