开发者

adding child with "getChildByName"?

I have a variable as following:

private var fotoSlide:FotoSlide;

and i am doing the following inside my code:

var data:Object = _dataProvider[0];
trace(data.type);//This gives back the string Foto
var slide:Sprite = new (getChildByName(data.type+"Slide"));
addChild(slide);

So if i'm declaring my variable with getChildByName the result should be FotoSlide. But it doesnt seem to work. I think it has to do because getChildByName can only开发者_如何学C be used when a child is added to the stage? Not sure thou. Anyone who knows what the problem is?


getChildbyName is looking for children in the display list, not member variables. It looks like you're trying to use it for reflection, which isn't what it does.

What are you actually trying to accomplish here? If it's just having a way to construct a type based on the string then you could do a simple switch statement:

// Assuming all *Slide objects implement ISlide
private function buildSlide(type:String):ISlide {
  switch (type) {
    case "Foto":
      return new FotoSlide();
    case "Text":
      return new TextSlide();
    // ...
  }
}

var data:Object = _dataProvider[0];
trace(data.type);//This gives back the string Foto
var slide:Sprite = this.builderSlide(data.type);
addChild(slide);

Or, create a hash with functions that return a new element of that type. For instance:

private var builders:Object = {
  "Foto" : function() { return new FotoSlide(); },
  "Text": function() { return new TextSlide(); },
  // ...
};

var data:Object = _dataProvider[0];
trace(data.type);//This gives back the string Foto
var slide:Sprite = this.builders[data.type]();
addChild(slide);

You might want to do some validation of the data.type value to make sure it's an expected type, depending on how much you trust the datasource.

The former is a bit more typesafe, but both should work.


try changing

var slide:Sprite = new (getChildByName(data.type+"Slide"));

to

var slide:Sprite = new Sprite(getChildByName(data.type+"Slide"));


You need to use getDefinitionByName which , provided the class exists will return the class Object you can then instantiate.

  var ClassName:Object = getDefinitionByName("ClassName");
  var instance:Sprite = new ClassName();

In your case :

   var data:Object = _dataProvider[0];

   var FotoSlideClass:Object = getDefinitionByName(data.type+"Slide");
   var slide:Sprite = new FotoSlideClass();
   addChild(slide);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜