2012-06-26 49 views
2

我想實現一個非常簡單的方法來存儲包含我單擊的最後一個特定「CustomObject」的變量。我想點擊其他對象被忽略。就拿下面的示例代碼,給出CustomObject擴展影片剪輯:使對象像AS3中的單選按鈕一樣

//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]; 
} 

這個偉大的工程每當我點擊squares-他們正好亮起預期。不過,我想實現一個功能: 1)存儲方形的楦我點擊進入文檔類 2)一個變量從所有其他方塊刪除光暈當我點擊另一個

任何反饋非常感謝!

回答

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屬性以及對它添加到的集合的引用。這樣,您可以簡單地將點擊事件添加到CustomObject類中,並使處理函數具有以下類似功能:

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

您先生是紳士和學者。這是一個讓班級管理自定義對象的天才想法。非常感謝! – Gigazelle