Reputation: 11
I made a Stopwatch class in JavaScript, and when a user clicks on a "start stopwatch" button, the stopwatch should start.
My problem is that when a user clicks the "start stopwatch" button, this
is referencing the button instead of the Stopwatch object.
Any suggestions?
Here is an example: https://c9.io/rjfreund/stopwatch/workspace/stopwatch.html
Upvotes: 1
Views: 255
Reputation: 147413
The value of a function's this
is set by how the function is called. For a listener, if assigned like:
element.onclick = instance.method;
then it will be called by the handler more or less as a method of the element, setting its this
to the element. Attaching the listener using other methods (addEventListener
and various library schemes) do the same thing.
You can use call
or apply
, but you can also wrap the function and call it to set this
to the object you want:
element.onclick = funciotn() {insance.method()};
You can also use bind
, which is provided by ES5, various libraries and shims.
Upvotes: 0
Reputation: 53311
This is the best I can do without code:
<a id="start_stopwatch" onclick="yourStopwatchClass.start.call(yourStopwatchClass)">Start stopwatch!</a>
call
refers the this
variable to whatever you pass in, in this case your Stopwatch
class.
Upvotes: 0
Reputation: 48761
Since you're using jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
...use .bind()
or .on()
to bind the handler, and set the object in the event-data.
$('.yourElement').on("click", {obj: yourObject}, function(event) {
alert(event.data.obj);
});
Upvotes: 3