Vous pouvez avoir une situation courante où vous commencez à charger certains éléments dans le constructeur, supposons une image d'arrière-plan. Ce code ne fonctionnerait pas correctement:
var object:TestObject = new TestObject(); //inside the contructor, the background image will start loading
object.background.width = 120; // this will not work, because the background is not loaded yet
Il y a beaucoup de façons de résoudre ce ...
Vous pouvez charger les actifs avant de créer l'objet, et après ils sont chargés de les envoyer complètement le constructeur en tant que paramètres.
Ou vous pouvez définir des propriétés à l'intérieur de l'objet qui sera affecté aux actifs chargés quand ils le chargement complet, quelque chose comme ceci:
//outside
object.BackgroundWidth = 120;
----------
//inside the class
public var BackgroundWidth:int;
private var background:Bitmap;
public function TestObject(){
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, assignProperties);
loader.load("img.png");
}
//this will make sure the width is applied to the background
//when it's loaded completely
private function assignProperties(e:Event){
background = Bitmap((event.currentTarget as LoaderInfo).content);
background.width = BackgroundWidth;
}
J'espère que cela a aidé.
Pouvez-vous montrer un exemple où 'if (object! = Null)' échoue? Il est difficile de voir de quelle autre façon vous seriez capable de dire s'il a une référence non nulle. Ou voulez-vous dire initialisé - comme toutes les propriétés ont été définies? –
Oui, initialisé. – Loop
pouvez-vous poster en quoi consiste l'initialisation? – Patrick