StarlingMVC Framework Chinese tutorial

Configuration and start

Starling project will configure StarlingMVC project, only a few lines of code. In starting to starling.display.Sprite's class inheritance, create an instance of StarlingMVC and passing it three parameters: Starling display the root object (an instance of the class start) object instances StarlingMVCConfig, and some Beans ( array or BeanProvider).

package com.mygame.views
{
    import com.creativebottle.starlingmvc.StarlingMVC;
    import com.creativebottle.starlingmvc.config.StarlingMVCConfig;
    import com.creativebottle.starlingmvc.views.ViewManager;
    import com.mygame.models.GameModel;

    import starling.core.Starling;
    import starling.display.Sprite;

    public class GameMain extends Sprite
    {
        private var starlingMVC:StarlingMVC;

        public function GameMain()
        {
            var config:StarlingMVCConfig = new StarlingMVCConfig();
            config.eventPackages = ["com.mygame.events"];
            config.viewPackages = ["com.mygame.views"];

            var beans:Array = [new GameModel(), new ViewManager(this)];

            starlingMVC = new StarlingMVC(this, config, beans);
        }
    }
}

Examples StarlingMVCConfig told StarlingMVC location of the event packet and package of view it should be handled. Beans array just a set group of objects, may include any type of object, the difference will be the frame. ( Translator's Note: only the frame processing view object in view the package of [ViewRemoved] tab, when dealing with [the EventHandler] label, only the processing of event type event package.)

Additional settings on the Flash Builder

Use Flash  Builder compiler products, AS compiler will be strictly non-standard Metadata peeling labels, unless otherwise specified. StarlingMVC custom label for the realization of powerful features automatic dependency injection is necessary, without these labels, StarlingMVC will have no effect.

The compiler charge Xu StarlingMVC custom label very brief introduction, just add a few lines of additional parameters can be compiled on the project.

Add translation parameters, right-click the project and select "Properties", then select "ActionScript Compiler", behind the "Additional compiler arguments" added:

-keep-as3-metadata+=Dispatcher
-keep-as3-metadata+=EventHandler
-keep-as3-metadata+=Inject
-keep-as3-metadata+=Juggler
-keep-as3-metadata+=PostConstruct
-keep-as3-metadata+=ViewAdded
-keep-as3-metadata+=ViewRemoved

StarlingMVC so it can work.

Beans

A Bean is an instance of an object to provide StarlingMVC managed. Bean can be injected, receiving the injection, as well as receiving events. In the configuration phase StarlingMVC, there are several ways to set Bean elements:

Object instance

var beans:Array = [new GameModel(), new ViewManager(this)];

Bean instance

var beans:Array = [new Bean(new GameModel()), new Bean(new ViewManager(this))];

Bean setting method provided above is not an example of the genius of contrast, but the second constructor parameter Bean may pass a id. Only provide id, you can use only when dependency injection. In addition, if no id, class type Bean will be stored in the frame as a key, if you have the same two types Bean, you must provide the id, otherwise the latter will cover the former. example:

var beans:Array = [new Bean(new GameModel(),"gameModelEasy"),new Bean(new GameModel(),"gameModelHard"), new ViewManager(this)];

BeanProvider examples

BeanProvider Bean is a collection of simple Bean same array, the bean within BeanProvider, may be any type, including BeanProvider.

package com.mygame.config
{
    import com.creativebottle.starlingmvc.beans.BeanProvider;
    import com.mygame.assets.AssetModel;
    import com.mygame.models.AudioModel;
    import com.mygame.models.GameModel;

    public class Models extends BeanProvider
    {
        public function Models()
        {
            beans = [new GameModel(), new Bean(new AudioModel(),"audioModel"), new AssetModel()];
        }
    }
}

With BeanProvider, you can use it as one of the elements in a manner to provide an array of bean:

var beans:Array = [new Models(), new ViewManager(this)];

ProtoBeans

ProtoBean Bean is being created will be injected. Bean general require a class instance, ProtoBean request and a definition of a class id.

var beans:Array = [new ProtoBean(Character,"character"), new ViewManager(this)];

As used herein ProtoBean will charge Xu StarlingMVC create an instance of the class for you. Each time it is injected, will instantiate a new instance of the class, in this case, "Character" class rather than as a single use as a general embodiment of the Bean. Let StarlingMVC framework to create an instance of a class, instead of using "new Character ()" to create benefits that the former can be injected, regulatory and other events to deal with all matters dependency injection.

Dependency Injection

Dependency injection occurs at all Bean and all the Starling object. In the disclosed properties or gettter / setter labeled with [the Inject] tag is no data dependencies. An injection can be defined:

package com.mygame.controllers
{
    public class GameController
    {
        [Inject]
        public var gameModel:GameModel;

        public function GameController():void
        {

        }
    }
}

Or to inject id, id when specifying if the Bean has provided the words:

package com.mygame.controllers
{
    public class GameController
    {
        [Inject(source="gameModel")]
        public var gameModel:GameModel;

        public function GameController():void
        {

        }
    }
}

In the above example, if an ordinary GameModel Bean, the frame will be created when a single embodiment it assignment configuration. If it is a Protobean, the framework creates an instance and then injected into a variable.

StarlingMVC also supports injecting Bean attributes. To use this function, there must be a source Bean id (used in the new configuration specified Bean id). Bean properties of injection, in [Inject] bean id + attribute name to add. "":

package com.mygame.controllers
{
    public class GameController
    {
        [Inject(source="gameModel")]
        public var gameModel:GameModel;

        [Inject(source="userModel.currentUser")]
        public var currentUser:User;

        public function GameController():void
        {

        }
    }
}

In the above example, userModel currentUser attribute properties will be injected onto our currentUser controller. This feature also supports recursion, if you want to inject currentUser the firstName property, you can do this:

[Inject(source="userModel.currentUser.firstName")]

.

Binding

Injecting operation also supports simple binding mechanism when the source object is changed, the properties will be injected automatically updated.

package com.mygame.controllers
{
    public class GameController
    {
        [Inject(source="gameModel")]
        public var gameModel:GameModel;

        [Inject(source="userModel.currentUser", bind="true")]
        public var currentUser:User;

        public function GameController():void
        {

        }
    }
}

As indicated above, use of a bind in [the Inject] tag = "true" parameters to achieve binding. When the change of currentUser property userModel, StarlingMVC will automatically update all injected using binding. This also applies to move getter / setters method This method can make changes to achieve the property code easily.

package com.mygame.controllers
{
    public class GameController
    {
        [Inject(source="gameModel")]
        public var gameModel:GameModel;

        [Inject(source="userModel.currentUser", bind="true")]
        public function set currentUser(value:User):void
        {
            _currentUser = value;

            // Do something to update your UI with the new value
        }

        public function get currentUser():User
        {
            return _currentUser;
        }
        private var _currentUser:User;

        public function GameController():void
        {

        }
    }
}

Binding and Starling juggler connected, which means that it will change automatically check the bindings every time advanceTime () method is called property. This differs from Flex provides immediate binding. Binding should be used with caution, because the properties are bound to change inspection is not a small overhead.

As automatic binding properties Alternatively, StarlingMVC supported by the failure to make way binding. This method is very effective with respect to automatically bind, because when the property updates it gives you more control. This function can be injected through a Bindings embodiment and a class "auto" parameters to achieve:

package com.mygame.controllers
{
    public class GameController
    {
        [Inject(source="gameModel")]
        public var gameModel:GameModel;

        [Inject(source="userModel.currentUser", bind="true", auto="false")]
        public function set currentUser(value:User):void
        {
            _currentUser = value;

            // Do something to update your UI with the new value
        }

        public function get currentUser():User
        {
            return _currentUser;
        }
        private var _currentUser:User;

        public function GameController():void
        {

        }
    }
}

package com.mygame.models
{
    public class UserModel
    {
        [Bindings]
        public var bindings:Bindings;

        public function set currentUser(value:User):void
        {
            if(value != _currentUser)
            {
                _currentUser = value;

                bindings.invalidate(this, "currentUser");
            }
        }

        public function get currentUser():User
        {
            return _currentUser;
        }
        private var _currentUser:User;
    }
}

event

Dispatch event

StarlingMVC events distributed through two channels: 1) StarlingMVC contains an instance of a global starling.events.EventDispatcher, a quick way to distribute the event is to use the dispatcher. The dispatcher can [the Dispatcher] metadata tag is injected into any of a Bean. 2) display object can use its own dispatchEvent () method dispatch events. This method is valid only when the event bubble set to true.

Handling Events

Event processing is added as indicated in the method disclosed in the bean [EventHandler (event = "")] metadata tag. Parameter in the tag event, there are two writing: one for the event type string

package com.mygame.controllers
{
    public class GameController
    {
        [EventHandler(event="scoreChanged")]
        public function scoreChanged(event:ScoreEvent):void
        {

        }
    }
}

Another string defined for the event:

package com.mygame.controllers
{
    public class GameController
    {
        [EventHandler(event="ScoreEvent.SCORE_CHANGED")]
        public function scoreChanged(event:ScoreEvent):void
        {

        }
    }
}

The benefits of using the second method, the type of event that StarlingMVC will check whether there is a real event initialization, if not, will throw an exception. It also can prevent incorrect word. ( Translator's Note: This is the reason the developers provided eventsPackage of StarlingMVC requirements.)

In both cases, the handler must accept and process a dispatched event. However, the second parameter [the EventHandler] Xu tab charging property you specify which events will be passed to the event handler. E.g:

package com.mygame.controllers
{
    public class GameController
    {
        [EventHandler(event="ScoreEvent.SCORE_CHANGED", properties="user, newScore")]
        public function scoreChanged(user:User, newScore:int):void
        {

        }
    }
}

As indicated above, StarlingMVC an event is not transmitted to the whole event function, but only pass the event of "user" and "newScore" attribute. Note: The type must match, otherwise it will error.

View Middleware

Middleware is a view to maintain a good way to control your view class and their code separation. View middleware settings, like other Bean. Use [ViewAdded] metadata tag to a view onto a view of the intermediate link. When the view is added after the displayed list, StarlingMVC will check all labeled with [ViewAdded] The method of label, if the type of the parameter is added view of a method of displaying the identified into the list of the same type of view, the display object is passed into the method. Similarly, [ViewRemoved] When the view is injected into the tab for the function to be executed when a listing is removed from the display.

package com.mygame.mediators
{
    public class GameMediator
    {
        private var view:Game;

        [ViewAdded]
        public function viewAdded(view:Game):void
        {
            this.view = view;
        }

        [ViewRemoved]
        public function viewRemoved(view:Game):void
        {
            this.view = null;
        }
    }
}

Bean's life cycle

In general, bean initialization is provided. However, after the bean is created, dependency injection and event listeners did not immediately available. In order to get a notification when bean injection is completed, we can add [PostConstruct] tag on a public method, this method will be automatically called after the injection is completed. Similarly, when a bean is destroyed, we labeled [The PreDestroy] discloses a method in tab. This feature is available on all standard bean and display object.

package com.mygame.controllers
{
    public class GameController
    {
        [Inject]
        public var gameModel:GameModel;

        [PostConstruct]
        public function postConstruct():void
        {
            // set up code here
        }

        [PreDestroy]
        public function preDestroy():void
        {
            // tear down code here
        }

        [EventHandler(event="ScoreEvent.SCORE_CHANGED", properties="user, newScore")]
        public function scoreChanged(user:User, newScore:int):void
        {

        }
    }
}

package com.mygame.controllers
{
    public class GameModel
    {
        [Bindings]
        public var bindings:Bindings;

        public function set score(value:int):void
        {
            if(value != _score)
            {
                _score = value;

                bindings.invalidate(this, "score");
            }
        }

        public function get score():int
        {
            return _score;
        }
        private var _score:int;
    }
}

Manually add, remove Bean

Manually add, remove bean is done through the event, distribute BeanEvent.ADD_BEAN event to add, a new bean processing, distribution BeanEvent.REMOVE_BEAN event bean removed from the system.

package com.mygame.view
{
    public class Game
    {
        public var gamePresentationModel:GamePresentationModel;

        [PostConstruct]
        public function postConstruct():void
        {
            gamePresentationModel = new GamePresentationModel();

            dispatchEvent(new BeanEvent(BeanEvent.ADD_BEAN, gamePresentationModel));
        }

        [PreDestroy]
        public function preDestroy():void
        {
            dispatchEvent(new BeanEvent(BeanEvent.REMOVE_BEAN, gamePresentationModel));

            gamePresentationModel = null;
        }
    }
}

As shown in the above, we create a Model for the view and as a bean add StarlingMVC. Model will be treated as a bean, and immediately gain an advantage injection and event handling.

Command mode

StarlingMVC include support for Command mode. On Command is essentially event-dispatch, execute, Bean was created when destroyed. , You need to add Command class definition in the bean to add a command frame.

package com.mygame.views
{
    import com.creativebottle.starlingmvc.StarlingMVC;
    import com.creativebottle.starlingmvc.config.StarlingMVCConfig;
    import com.creativebottle.starlingmvc.views.ViewManager;
    import com.mygame.models.GameModel;

    import starling.core.Starling;
    import starling.display.Sprite;

    public class GameMain extends Sprite
    {
        private var starlingMVC:StarlingMVC;

        public function GameMain()
        {
            var config:StarlingMVCConfig = new StarlingMVCConfig();
            config.eventPackages = ["com.mygame.events"];
            config.viewPackages = ["com.mygame.views"];

            var beans:Array = [new GameModel(), new ViewManager(this), new Command(DoSomethingEvent.DO_SOMETHING, DoSomethingCommand)];

            starlingMVC = new StarlingMVC(this, config, beans);
        }
    }
}

This event is mapped to Command. Like other classes can command received as bean injection, but not receives the event only a single command execution period in memory. In the method of performing the command is labeled as [the Execute] tab.

package com.mygame.commands
{
    import com.mygame.events.NavigationEvent;
    import com.mygame.models.BubbleModel;

    import starling.events.EventDispatcher;

    public class DoSomethingCommand
    {
        [Dispatcher]
        public var dispatcher:EventDispatcher;

        [Inject]
        public var bubbleModel:BubbleModel;

        [Execute]
        public function execute(event:DoSomethingEvent):void
        {
            trace("did something!");
        }
    }
}

As shown in the above, when DoSomethingEvent.DO_SOMETHING event is dispatched, StarlingMVC will create an instance of a DoSomethingCommand, execution execute method, and then destroy it. Command class can include an optional parameter in a runOnce label.

package com.mygame.views
{
    import com.creativebottle.starlingmvc.StarlingMVC;
    import com.creativebottle.starlingmvc.config.StarlingMVCConfig;
    import com.creativebottle.starlingmvc.views.ViewManager;
    import com.mygame.models.GameModel;

    import starling.core.Starling;
    import starling.display.Sprite;

    public class GameMain extends Sprite
    {
        private var starlingMVC:StarlingMVC;

        public function GameMain()
        {
            var config:StarlingMVCConfig = new StarlingMVCConfig();
            config.eventPackages = ["com.mygame.events"];
            config.viewPackages = ["com.mygame.views"];

            var beans:Array = [new GameModel(), new ViewManager(this), new Command(DoSomethingEvent.DO_SOMETHING, DoSomethingCommand, true)];

            starlingMVC = new StarlingMVC(this, config, beans);
        }
    }
}

In this example, a command bean is added to this statement: new Command (DoSomethingEvent.DO_SOMETHING, DoSomethingCommand, true). The last parameter true, identifies the comand only be run once. So, when DO_SOMETHING event is dispatched, DoSomethingCommand the instance is created framework, implementation, and finally destroyed and removed from the map. This feature is very useful when initializing ( Translator's Note: refers to perform once).

EventMap

EventMap is a utility class for creating and managing event listeners. Using EventMap exclusively to create listeners within your class makes cleanup very easy.

EventMap is a creation, management, event listening tools. EventMap created using the event monitor easy to clean.

package com.mygame.mediators
{
    import com.creativebottle.starlingmvc.events.EventMap;

    public class GameMediator
    {
        private var eventMap:EventMap = new EventMap();

        [ViewAdded]
        public function viewAdded(view:Game):void
        {
            eventMap.addMap(view.playButton,TouchEvent.TOUCH, playButtonTouched);
            eventMap.addMap(view.instructionsButton,TouchEvent.TOUCH, instructionsTouched);
        }

        [ViewRemoved]
        public function viewRemoved(view:Game):void
        {
            event.removeAllMappedEvents();
        }

        private function playButtonTouched(event:TouchEvent):void
        {

        }

        private function instructionsButtonTouched(event:TouchEvent):void
        {

        }
    }
}

Juggler

Starling's juggler used to manage all animations within the game. For a convenient use Juggler class must implement IAnimatable interface definitions

advanceTime(time:Number)

method. Global juggler references can be accessed through this instance attributes: Starling.juggler. And this property may be used [Juggler] tag is directly injected into the bean. ( Translator's Note: StarlingMVC1.1 source has a dedicated Processor for processing Juggler implantation)

package com.mygame.mediators
 {
    import com.creativebottle.starlingmvc.events.EventMap;

    public class GameMediator implements IAnimatable
    {
        [Juggler]
        public var juggler:Juggler;

        [ViewAdded]
        public function viewAdded(view:Game):void
        {
            juggler.add(this);
        }

        [ViewRemoved]
        public function viewRemoved(view:Game):void
        {
            juggler.remove(this);
        }

        public function advanceTime(time:Number):void
        {
            // do some animation logic
        }
    }
 }

ViewManager

ViewManager class is a tool through which can be used to add and delete view on the stage. When we create ViewManager case, we need to pass a root display object. So that we can easily add visual interactive content in any position Starling by ViewManager.

Setting the View

Call setView will remove the existing view and add a new view. ViewManager view processing example, and add it to the stack.

package com.mygame.controllers
{
    public class NavigationController
    {
        [Inject]
        public var viewManager:ViewManager;

        [EventHandler(event="NavigationEvent.NAVIGATE_TO_VIEW", properties="viewClass")]
        public function navigateToView(viewClass:Class):void
        {
            viewManager.setView(viewClass);
        }
    }
}

Add View

Call addView method to add a new view on an existing view. Here GameHUD added addView type views by conventional methods to the view manager.

package com.mygame.views
{
    public class Game
    {
        [Inject]
        public var viewManager:ViewManager;

        private var hud:GameHUD;

        [PostConstruct]
        public function postConstruct():void
        {
            hud = new GameHUD();

            viewManager.addView(hud);
        }
    }
}

View removed

You can delete the view stack developed by calling removeView.

Remove all views

Call removeAll remove all existing views in the stack. This method is called automatically when you call setView () of.

Reproduced in: https: //my.oschina.net/zhepama/blog/265038

Guess you like

Origin blog.csdn.net/weixin_33778544/article/details/91927358