简体   繁体   中英

Actionscript: how can I add a custom property to an instance of Image?

var image:Image = new Image();
image.property_1 = "abcdefg";

it can't compile as the Flash builder says:

Description  Resource     Path      Location       Type
1119: Access of possibly undefined property jdkfjds through a reference with static type mx.controls:Image.
             adm.mxml     /adm/src  Line 209       Flex Problem

How can I do that? Or I need to extends the Image class? It's quite boring.

If you know all the attributes you need to add and they won't change (often), this will work.

package mypackage
{
    import mx.controls.Image;
    public class ExtendedImage extends Image
    {
        public function ExtendedImage()
        {
            super();
        }

        //option 1
        private var prop1:String = "";
        public function get property_1():String
        {
            return prop1;
        }
        public function set property_1(val:String):void
        {
            prop1 = val;
        }

        //option 2
        public var property_2:String = "";
    }
}

Image is not declared as dynamic class so you can`t dynamically add properties.

Derive from Image and extend the class with the dynamic keyword:

package mypackage
{
  import mx.controls.Image;

  public dynamic class DynamicImage extends Image {}
}

and now this will work:

import mypackage.DynamicImage;

var image:DynamicImage = new DynamicImage();
image.property_1 = "abcdefg";

But you can use container for your image and add extra properties there; or use dictionary with image as a key and property as a value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM