Component Inspector, properties always null?

I've created a small component in Flash CS4, and I have associated my MyComp symbol with it's respective MyComp class. The code in MyComp.as looks as follows:

package {
    import flash.display.MovieClip;

    public class MyComp extends MovieClip
    {
        public function MyComp()
        {
            trace(this.test);
        }

        private var _test:String;

        [Inspectable(defaultValue="blah")]
        public function get test():String
        {
            return this._test;
        }

        public function set test(v:String):void
        {
            this._test = v;
        }
    }
}

When I drag the component to a test FLA, the component's properties are all showing up as per the Inspectable[] meta tag. But when I set the properties in the Component Inspector, the value is always null, despite what the Component Inspector says.

When tracing for example test, it always outputs null?

How do I get the Component Inspector's values to reflect in the component at runtime?


The order of operations with components and inspectable properties can be a bit tricky. Keith Peters (Bit-101) wrote up a nice overview of the problems with inspectable getters and setters.

The issue, in particular, is that the constructor gets called PRIOR to the inspectable properties being set. One nice way around this is to make your constructor setup a listener for the EXIT_FRAME event, which will run during the same frame, just after everything else is done. For example:

package {

    import flash.display.MovieClip;
    import flash.events.Event;

    public class SampleComponent extends MovieClip {

        private var _foo:Number;

        public function SampleComponent() {
            trace("SampleComponent: constructor");
            addEventListener(Event.EXIT_FRAME, onReady);
        }

        [Inspectable]
        public function get foo():Number {
            trace("SampleComponent: get foo: " + _foo);
            return _foo;
        }

        public function set foo(value:Number):void {
            trace("SampleComponent: set foo: " + value);
            _foo = value;
        }

        private function onReady(event:Event):void {
            trace("SampleComponent: ready!");
            removeEventListener(Event.EXIT_FRAME, onReady);
        }
    }
}

You can just use the text string "exitFrame", like this:

addEventListener( "exitFrame", onExitFrame );

The event fires, it seems the Event class is just missing the definition.

链接地址: http://www.djcxy.com/p/17842.html

上一篇: 在闪光灯CS4中的滚动条

下一篇: 组件检查器,属性始终为空?