PDA

View Full Version : Event handlers within objects


fleeklee
07-27-2003, 11:48 PM
Hi,

I have the following code

MyClass.prototype.myVar = "some value";

MyClass.prototype.buildScreen = function() {

[create button]

button.onPress = ???

}

MyClass.prototype.foo = function() {
trace(this.myVar);
}

My problem is that I want the onPress event handler to cause a call to foo();

I've tried

button.onPress = function() {
this.foo();
}

but "this" in this context is the button.

I've also tried things similar to

button.onPress = this.foo;

but the "this" reference within foo() becomes the button as well, making "myVar" unavailable.

Any ideas besides storing the MyClass instance in a global?

Thanks,
Ken

ebmGameGuy
07-28-2003, 01:38 AM
Unless you make the button a subclass of MyClass it is actually independent of MyClass so you would need to use the full address to the function:

button.onPress = MyClassInstanceName.foo;

senocular
07-28-2003, 06:49 AM
var thisClassInstance = this;
button.onPress = function() {
thisClassInstance.foo();
}

buggedcom
07-28-2003, 09:47 PM
or


button.callback = this;
button.onPress = function() {
this.callback.foo();
}

but i think this is slower, is it not?

fleeklee
07-29-2003, 01:49 AM
Sweet. Thanks!

I'm not sure what you mean by slower. Slower to build the screen? Slower to process the click? I can live with an extra couple milliseconds.