PDA

View Full Version : Button handler call a class method - "this" ?



mattajlsm
11 May 2007, 6:13 AM
Hello,

I'm new to Ext and not so old with Javascript...

I defined a button with Ext.Button. When the user click on the button, I want it to call a method of an object class instance.

Well let say something like this :
this is my Class

function MyTestClass(property) {
this.property=property;
}

MyTestClass.prototype.myMethod=function(){
alert(this.property);
}

I instance a new object from this Class :

var objTest = new MyTestClass('hello');

and then make the button :

var button1 = new Ext.Button($('button1'),{
text:'bouton1',
handler:objTest.myMethod,
});
(assuming there's a div in the body with id="button1")

Well I thought clicking on the button will alert "hello", but it doesn't :
"undefined" is alerted instead.

It actually comes from "this" in myMethod which doesn't refers to objTest but to the button object itself ...

Maybe I miss something about Javascript or Ext...

Any Idea how I can get this work ?
Thanks,

Matt

tryanDLS
11 May 2007, 6:39 AM
You need to learn/understand JS variable scoping - this is not an Ext issue, per say. Refer to the Javascipt newbies thread at the top of this forum for links to references to get a better handle on scope, OO, etc.

mattajlsm
11 May 2007, 7:02 AM
I guess you're right...
I read a lot of documentation about oop with javascript during the whole day but didn't really fix how I should do to make this simple thing working ?

Before I use Ext, I had a simple button


<button onclick="objTest.myMethod()">button</button>


which work perfectly, I just wanted to use an Ext button instead
but well... I go on reading so !

Regards,
matt

haibijon
11 May 2007, 7:07 AM
var button1 = new Ext.Button($('button1'),{
text:'bouton1',
handler:objTest.myMethod,
});


Will not work because you're telling the button to call a copy of the function objText.myMethod outside of the objTest scope. The code below should work, see how we pass the object itself as the scope for which the handler will be called. Also, with Ext you don't need to pass around DOM references like you did with $('button1'), simply pass the ID and Ext will take care of the rest.



var button1 = new Ext.Button( 'button1',{
text:'My Button', // text to display for button
handler: objTest.myMethod, // method to call
scope: objTest // object (scope) you want the method called from
});

mattajlsm
11 May 2007, 8:00 AM
Thanks a lot for your explanation haibijon !
I test with "scope: objTest" and it works like a charm :D
thanks too for the advice about DOM references.
Regards,
Matt