使对象的行为类似于AS3中的单选按钮

时间:2012-06-26 00:52:22

标签: actionscript-3 flash flash-cs5.5

我想实现一种非常简单的方法来存储包含我单击的最后一个特定“CustomObject”的变量。我希望忽略其他对象的点击。以下示例代码为例,给定CustomObject扩展MovieClip:

//Code within the Document Class:
var square1:CustomObject = new CustomObject();
var square2:CustomObject = new CustomObject();
var square3:CustomObject = new CustomObject();
var triangle1:DifferentObject= new DifferentObject();
square1.x=100; square2.x=200; square3.x=300;
addChild(square1);
addChild(square2);
addChild(square3);
addChild(triangle1);

//Code within the CustomObject Class:
this.addEventListener(MouseEvent.CLICK,radioButtonGlow);
public function radioButtonGlow(e:MouseEvent):void
{
    var myGlow:GlowFilter = new GlowFilter();
    myGlow.color = 0xFF0000;
    myGlow.blurX = 25;
    myGlow.blurY = 25;
    this.filters = [myGlow];
}

无论什么时候点击方块,这都很有效 - 它们完全按照预期亮起。但是,我想实现一个功能: 1)将我点击的最后一个方格存储到文档类中的变量中 2)当我点击另一个方块时,从所有其他方块中移除光晕

非常感谢任何反馈!

1 个答案:

答案 0 :(得分:1)

我建议创建一个充当CustomObject实例集合的类,并以这种方式管理它们(即确保只能选择其中一个集合等)。

样品:

public class CustomCollection
{

    // Properties.
    private var _selected:CustomObject;
    private var _items:Array = [];

    // Filters.
    private const GLOW:GlowFilter = new GlowFilter(0xFF0000, 25, 25);


    // Constructor.
    // @param amt The amount of CustomObjects that should belong to this collection.
    // @param container The container to add the CustomObjects to.
    public function CustomCollection(amt:int, container:Sprite)
    {
        for(var i:int = 0; i < amt; i++)
        {
            var rb:CustomObject = new CustomObject();
            rb.x = i * 100;

            _items.push(rb);
            container.addChild(rb);
        }
    }


    // Selects a CustomObject at the specified index.
    // @param index The index of the CustomObject to select.
    public function select(index:int):void
    {
        for(var i:int = 0; i < _items.length; i++)
        {
            if(i == index)
            {
                _selected = _items[i];
                _selected.filters = [GLOW];

                continue;
            }

            _items[i].filters = [];
        }
    }


    // The currently selected CustomObject.
    public function get selected():CustomObject
    {
        return _selected;
    }


    // A copy of the array of CustomObjects associated with this collection.
    public function get items():Array
    {
        return _items.slice();
    }
}

然后,您可以将文档类中的代码修改为:

var collection:CustomCollection = new CustomCollection(3, this);
collection.select(1);

您需要为处理选择按钮的点击事件添加自己的逻辑。我建议为每个CustomObject添加一个index属性,以及对它添加到的集合的引用。这样,您可以简单地将click事件添加到CustomObject类中,并使处理程序功能类似于:

private function _click(e:MouseEvent):void
{
    _collection.select(index);
}