如何从不是孩子父母的班级中删除孩子?

时间:2015-09-14 13:39:03

标签: actionscript-3

我有一个主类,我在其中创建一个类的实例并使用addChild()添加它们。我也有按钮和他们各自的课程。我想从我的按钮类中删除带有removeChild()的实例,而不是从主类中删除。这甚至可能吗?

mainClass中的一个对象:

public static var start_icon_:start_icon = new start_icon();
addChild(start_icon_);

我希望能够:

removeChild之(start_icon_);在一个不是mainClass的类中。

1 个答案:

答案 0 :(得分:0)

First, a class does not have a parent or child; an instance has a parent or child. It's a good idea to try to get used to thinking that way. When you make something static you are making the code associated with the class, which is not specific to any particular instance. Meanwhile, methods like addChild and removeChild are instance functions, because they necessarily relate to specific instances of the class. So when you try to do things like expose a function globally by making it static, but want to do instance specific things like removeChild, you can get rather tangled.

To solve your problem, there are a few solutions.

You can simply "reach upward" to remove the child. For example, parent.removeChild(this) will remove a child from its parent. If you know the parent is a MainClass instance, you can cast and reference a property on it: parent.removeChild(MainClass(parent).start_icon). (start_icon should not be static.) You can even reach parent.parent. and so on.

That's not a great solution, though, because you are making the code assume a certain parent/child hierarchy. If you move things around it will break at runtime. A better solution (already mentioned in the comments) is to use events. For example:

class MainClass extends Sprite {
    public var startIcon:StartIcon = new StartIcon();

    public function MainClass() {
        addChild(startIcon);
        addEventListener("removeStartIcon", removeStartIcon);
    }

    private function removeStartIcon(e:Event):void {
        removeChild(startIcon);
    }
}

// From start icon, or any child (or children's child, etc) of main class instance:
dispatchEvent(new Event("removeStartIcon", true)); // bubbles=true, to trickle up the display hierarchy

Lastly, you can use the singleton pattern. Like others, I don't recommend this, but it is a quick and easy way to make a single instance of a class behave globally. The gist is that you expose a static reference to a single instance of your class, with the assumption you only ever need a single instance of that class. Then you can reference instance functions and properties from anywhere through the static reference of the class to its single instance. For example:

class MainClass extends Sprite {
    public static var main:MainClass;
    public var startIcon:StartIcon = new StartIcon();
    public function MainClass() {
        main = this;
        addChild(startIcon);
    }
    public function removeStartIcon():void {
        removeChild(startIcon);
    }
}

Now from anywhere you can do this: MainClass.main.removeStartIcon() or even MainClass.main.removeChild(MainClass.main.startIcon).