Yes it would be nice, but it does not work :(. The second argument of the click() is not passed to the count method.
-----Original Message----- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Blair Mitchelmore Sent: Tuesday, October 24, 2006 11:58 PM To: jQuery Discussion. Subject: Re: [jQuery] jQuery and OOP A technique you might find slightly less ugly is passing 'this' as an argument when you bind the event. If I recall correctly, jQuery has the ability to pass an arbitrary number of additional arguments as an additional argument array to the event bind function. function Counter() { $('#btnCounter').click(this.count,[this]); 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(e,self) { self.button.attr('value', self.nr++); } } -- blair Kolman Nándor 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 discuss@jquery.com http://jquery.com/discuss/ _______________________________________________ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/