收录日期:2020/10/23 10:16:48 时间:2010-09-07 01:58:15 标签:flash,actionscript-3

Trying to load images dynamically from library NOT externally since i want these images to be loaded when the site is launched. Basically i have several buttons, each button returns an event that throws a specific image name to grab. Here is the function;

function sendDisplayData(e:MouseEvent){
    display_mc.displayName.text = e.currentTarget.parent.menuItemName.text; //name of image eg. "myImageName" in the library;

    //create the image object 
    var imgObj:Object = e.currentTarget.parent.menuItemName.text;
    addChild(imgObj);
}

So basically when the function is called, i want to instantiate the names to the names of the actual movieclips in the library. The function below works but only for one image.

function sendDisplayData(e:MouseEvent){
    display_mc.displayName.text = e.currentTarget.parent.menuItemName.text;

    //create the image object 
    var image:Salads = new Salads(); //the class of the image is "Salads"
    display_mc.addChild(Salads);
} 

So how can i make this function dynamic by using a String and then grabbing the image related to that string from the library.

Another option is using getDefinitionByName:

function getDisplayObject(linkage:String):DisplayObject {
    var clazz:Class = getDefinitionByName(linkage) as Class;
    return new clazz();
}

So, if you already have the proper linkage name, you could do something like this:

function sendDisplayData(e:MouseEvent){
    //create the image object 
    var imgObj:DisplayObject = getDisplayObject(e.currentTarget.parent.menuItemName.text);
    addChild(imgObj);
}

There are many options, here one of the simpler ones , although not really flexible.

public class Inventory
{
    public static function getMovieClipByName(value:String):MovieClip
    {
       switch(value )
       {
          case "Salads":
            return new Salads();
            break;

          //etc....

          default:
            return null;
     }
   }
}

You could also put all your image objects in an array make sure to assign a name to each of them and then use the Array some() method to find the object corresponding to the name and return it.

Then you could do this:

function sendDisplayData(e:MouseEvent){
    var _name:String = display_mc.displayName.text = e.currentTarget.parent.menuItemName.text;

    //create the image object 
    var image:MovieCLip = Inventory.getMovieClipByName(_name);
    display_mc.addChild(image);
}