Seeking to create an event handler that registers a callback and iterates based on the event.
An early, working example is something like this:
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);
Now I want to actually write something js I could use. Here is the current construction:
//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)
The error I receive is Uncaught TypeError: Object #<CountMe> has no method 'addEventListener'
Given an html page like this:
<html>
<body>
<div style="width:50px; height:50px; background-color:red;" id="square">
</div>
</body>
</html>
My questions are:
- How should this be constructed so
onclick
events function as they do in the first method? - In the method
countClick
what context is the nested this in? The instance of theCountMe
class I suspect, just want someone else's take.