Reputation: 279
I am working on a set of "generic" classes I use frequently in different AS3 projects. One of these classes is the Image class (extends MovieClip) which simply takes an URL, generates a loader than loads it and adds it as a child. In the aim of making it more generic, I thought of adding a callback as a parameter that could contain certain messages related to resizing the image and such (I can't resize any Image before the loader inside it is loaded since it's width and height will be 0 until then so it's necessary to wait for loading and handling such operations using event listeners in parent MovieClips is not convenient if there's a huge amount of images being loaded).
Here is my current implementation:
public class Image extends MovieClip {
public var self:MovieClip; //fixes scope issues when nesting functions
private var url:String;
private var callback:Function;
public function Image(url:String, callback:Function) {
this.self = this; //fixes scope issues when nesting functions
this.url = url;
this.callback = callback;
this.loadAndDraw();
}
public function loadAndDraw():void {
var l:Loader = new Loader();
l.contentLoaderInfo.addEventListener(Event.COMPLETE, function doneLoading(evt:Event) {
self.addChild(evt.currentTarget.loader);
callback();
});
l.load(new URLRequest(this.url));
}
}
Now, the problem with this is I'm having trouble writing the callback functions. I'm uncertain about how am I meant to refer to the 'caller', which makes me think there's a better way of doing this. What do you suggest?
Upvotes: 0
Views: 1268
Reputation: 3728
You could pass a reference to the Image
instance in the callback function.
public class Image extends MovieClip {
public var self:MovieClip; //fixes scope issues when nesting functions
private var url:String;
private var callback:Function;
public function Image(url:String, callback:Function) {
this.self = this; //fixes scope issues when nesting functions
this.url = url;
this.callback = callback;
this.loadAndDraw();
}
public function loadAndDraw():void {
var l:Loader = new Loader();
l.contentLoaderInfo.addEventListener(Event.COMPLETE, function doneLoading(evt:Event) {
self.addChild(evt.currentTarget.loader);
callback(self);
});
l.load(new URLRequest(this.url));
}
}
Then, your callback
function would have to accept that as a parameter:
var someImage:Image = new Image("http://some.valid.url/image.jpg", someCallback);
private function someCallback($caller:Image):void
{
// do something with $caller...
}
Upvotes: 2