Mike's approach can be expanded to a complex ajax application. Closures and element properties are natural ways to associate instance data with elements in jQuery.
-----Original Message----- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Kolman Nándor Sent: Tuesday, October 24, 2006 10:49 AM To: jQuery Discussion. Subject: Re: [jQuery] jQuery and OOP That is really nice and handy you wrote :), but I am writing a complex ajax application. I just created a simple scenario to show what I want. So yes, I really need it. -----Original Message----- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Michael Geary Sent: Tuesday, October 24, 2006 4:23 PM To: 'jQuery Discussion.' Subject: Re: [jQuery] jQuery and OOP Do you really need an object at all? This (pun intended) would do the same thing as all the code you listed: $(function() { var $btn = $('#btnCounter'), nr = 0; $btn.click( function() { $btn.attr( 'value', nr++ ); }); }); -Mike > From: Kolman Nándor > > 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? _______________________________________________ jQuery mailing list [email protected] http://jquery.com/discuss/
