I'm in a little over my head here with OOP in actionscript. I've got a Display class that captures a video stream. I'm trying to create a set of basic stop / record buttons to control the camera. Apparently I can't declare functions which access this
or any variables that would allow me to identify and stop the clip. The compiler (I'm using Haxe) throws the error :
video/Webcam.hx:96: characters 10-开发者_运维百科14 : Cannot access this from a static function
I might be approaching this the wrong way. Here's some (abbreviated) code:
class Webcam extends Display {
var nc : flash.net.NetConnection;
...
private function addControls(){
var stopIcon = new StopIcon();
var b = new flash.display.MovieClip();
b.addChild(stopIcon);
b.useHandCursor = true;
b.addEventListener(flash.events.MouseEvent.CLICK,function() {
trace(this);
this.stopStream()
});
b.x = 210;
b.y = 20;
}
...
}
I'm using Haxe to compile to AS3. There's a list of deltas here http://haxe.org/doc/flash/as2_compare that doesn't seem to cover this issue, so I believe this is a problem I have with AS. It's possible that it's compiler related, but I hope not because I've really liked Haxe so far.
How do you create UI elements associated with an object instance if the actionscript compiler treats these functions as static?
I believe this is due to the use of an anonymous function in your MouseEvent.CLICK handler without using the Event itself. The event handler takes an argument, which is the MouseEvent itself. So, you have a to do one of the following:
b.addEventListener(flash.events.MouseEvent.CLICK, function($evt:MouseEvent) {
trace($evt.target.parent);
$evt.target.parent.stopStream(); // May require casting, but probably not
}
OR
b.addEventListener(flash.events.MouseEvent.CLICK, __handleStopClick);
private function __handleStopClick($evt:MouseEvent):void {
this.stopStream();
}
Another common way to do it is the following:
private function addControls(){
...
var self = this;
b.addEventListener(flash.events.MouseEvent.CLICK,function() {
self.stopStream()
});
...
}
The advantage is that "self" is correctly typed and doesn't require casting. We are considering to add "this" as the default scope in such cases which will make the "self" trick unnecessary.
精彩评论