Hi,
I am new to jQuery, and I have a question concerning object oriented
programming. I have created a sample scenario.
In the HTML code I add a button:
<input type="button" value="Count" id="btnCounter" />
In js, I create a class called Counter. In the constructor I add an event
handler to the click event of the button. The function I specify as the handler
is a method of the Counter class. I also store the button and the nr (the
current value of the counter) as an object property.
function Counter() {
$('#btnCounter').click(this.count);
this.button = $('#btnCounter');
this.nr = 0;
}
In the count method I set the incremented value of the counter to the text of
the button.
Counter.prototype = {
count: function() {
this.button.attr('value', this.nr++);
}
}
And I need to create the object in the load event:
$(window).load(function() {
new Counter();
});
If I try to run the code I get: 'this.button has no properties'. I know that
the 'this' in the count method will be the target of the event (the button).
But that is not what I need, it is the reference of the Counter object.
If I rewrite the constructor I can make it work:
function Counter() {
var oThis = this;
$('#btnCounter').click(
function() {
oThis.count();
}
);
this.button = $('#btnCounter');
this.nr = 0;
}
But this is quite ugly :(. Is there a nicer way to achieve this?
Thx
_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/