how do I make non-document-class classes 'aware' of stage components in Flash AS3?

后端 未结 5 524
余生分开走
余生分开走 2021-01-28 05:56

I am working on a text adventure game which will have at least a few components (a text area for narrative and text input for user input) on the stage at all times. Therefore, I

5条回答
  •  清酒与你
    2021-01-28 06:58

    I would recommend the Service Locator Pattern for this. The most naive approach would be to create a resource class which contains public static variables. Then in your document class you assign the stage instances to the corresponding static variable in the resource class. Then you can simply access these stage components anywhere.

    var someTextArea = Resource.TA; //probably should rename to something more meaningful
    

    For something a little more ingenious you should read the article I linked to.

    I think this is better than the dependency injection as constructor injection could lead to huge parameter list as you might add more items to the stage, and I am not so fond on setter injection as it is easy to forget to set them.

    EDIT:

    Just to make it a bit more clear I thought I would add some code :)

    Resource class

    package
    {
        //TODO imports
        public class Resource
        {
            public static var TA:TextArea;
            public static var TI:TextInput;
        }
    }
    

    Document class

    //....setup function
    Resource.TA = myTA; //myTA is the name of the instance on stage
    Resource.TI = myTI;
    

    Foo class

    Resource.TA.x = 100;
    //or
    _myClassMemberVariable = Resource.TA;
    _myClassMemberVariable.x = 100;
    

提交回复
热议问题