Note that there are some explanatory texts on larger screens.

plurals
  1. POHow Do I Access Event Listeners on an instance of class?
    text
    copied!<p>Seeking to create an event handler that registers a callback and iterates based on the event.</p> <p>An early, working example is something like this:</p> <pre><code>var elt = document.getElementById("square"), clickCount = 0; // call a priviledged method with access to prviate vars from // outer scope var count = function () { clickCount += 1; alert("you clicked me " + clickCount + " times!"); }; elt.addEventListener("click", count, false); </code></pre> <p>Now I want to actually write something js I could use. Here is the current construction:</p> <pre><code>//Create a class object function CountMe () { //privately scoped variables var clickCount = 0; //methods on 'class' CountMe this.countClick = function () { //who's context am I in? this.addCount(); alert("you clicked me " + clickCount + " times!"); }; this.addCount = function() { clickCount += 1 }; }; // Create an instance of countMe class var clickMe = new CountMe(); //Add an event listener for clicks document.getElementById("square").addEventListener("click", clickMe.countClick ,false) </code></pre> <p>The error I receive is <code>Uncaught TypeError: Object #&lt;CountMe&gt; has no method 'addEventListener'</code> Given an html page like this:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div style="width:50px; height:50px; background-color:red;" id="square"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>My questions are: </p> <ul> <li>How should this be constructed so <code>onclick</code> events function as they do in the first method?</li> <li>In the method <code>countClick</code> what context is the nested this in? The instance of the <code>CountMe</code> class I suspect, just want someone else's take.</li> </ul>
 

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