I have an object that counts chars in an input and displays the number of chars in a div next to the input. I want to add a click event listener to the div that when clicked invokes a function in the object that created the div. I’m confusing myself now so here is some code:
var CharDisplay = function(input, max) {
this.input = input;
this.maxChars = max;
this.direction = "countUp";
this.div = document.createElement("div");
this.div.setAttribute("class", "charCounter");
this.input.parentNode.appendChild(this.div);
var that = this; // I don't like doing this
// This function toggles the direction property and tells the extension
// to update localStorage with the new state of this char counter
var toggleDirection = function() {
that.direction = that.direction === "countUp" ? "countDown" : "countUp";
that.update();
chrome.extension.sendRequest({
"method" : "updateCharCounter",
"id" : that.input.id,
"state" : {
"direction" : that.direction,
"limit" : that.maxChars
}
});
}
this.div.addEventListener("click", toggleDirection);
}
The behaviour I want is that when the div is clicked the Char Counter switches between counting down (’15 chars left’) and counting up (’30 of 45 chars’). I store the state of the char counter in localStorage so that whatever state the user left the char counter in they will find it that way when they come back to it.
Now this code actually works fine but I can’t escape the feeling that there is a more elegant way of doing it. I had to add the var that = this to get it to work but I always feel like that is a ‘hack’ and I try to avoid it if I can.
Can you think of a better way of achieving this or should I stop trying to fix what isn’t broke?
The
var that = thistrick is quite common in JavaScript.The alternative is to bind the function to a given context:
This function returns a function that, when called, will call
funwith the givencontext.You can use it like this:
With this,
toggleDirectionwill be called withthisas context (thisintoggleDirectionwill be the same as the one at the time you calledaddEventListener).See also
Function.bind.