Nice question, Kolman.

AFAIK, and I would love to hear different, is that this (ha ha) is the
proper way to do it in Ecmascript languages. In fact, in 'neater' OOP
languages like Java the same problem would occur if you had two
parallel sets of objects, as we have here with the DOM and
user-constructed objects; each instance needs to somehow reference its
partner instance. It seems to be a limitation of OOP that there is no
'natural' way to do this.

Chris

On 10/24/06, Kolman Nándor <[EMAIL PROTECTED]> wrote:
> 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/
>


-- 
Chris Ovenden

http://thepeer.blogspot.com
"Imagine all the people / Sharing all the world"

_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/

Reply via email to