`

StarlingMVC:为Starling量身打造的MVC框架

阅读更多

详细了解StarlingMVC框架,请登录其官方站点:

http://creativebottle.github.com/starlingMVC/

 

以下中文翻译转自Starling中文站,仅供部分参考之用:

http://www.starlinglib.com/wiki/News:StarlingMVC

 

StarlingMVC是一个为使用Starling来开发游戏的MVC框架。这个框架的特性方面,很像Swiz和RobotLegs。特性列表如下:

  • 依赖注入(DI)/控制反转(IOC)
  • 视图代理(View Mediation)
  • 事件捕获(Event Handling)
  • 非侵入性框架
  • 配置简单
  • 容易扩展
  • 包含了很多对您的游戏有帮助的工具

StarlingMVC 框架是基于 Apache License 2.0协议开源的.

目录

 [隐藏

Requirements

Contributors

安装

在线获取StarlingMVC项目并通过几行代码从Starling项目中配置StarlingMVC。你必须在Starling显示类(starling.display.*)中实例化StarlingMVC事例,并在StarlingMVCConfig中传入Starling的显示对象。

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), 
Starling.juggler];
 
            starlingMVC = new StarlingMVC(this, config, beans);
        }
    }
}

在StarlingMVCConfig类中,我们必须告诉StarlingMVC有哪些事件包和视图包以便StarlingMVC调用。beans数组实际上是一个对象集合,这个集合可以存入任何类型的对象。框架对他们进行相应的处理。

Beans

Bean是为StarlingMVC提供对象管理的一个工具,Bean可以接受注入操作,并处理相应的事件。Bean为StarlingMVC提供了几种可用的方法:

Object 实例

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

Bean 多实例

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

上面的代码,提供了一个Bean实例,但是并没有进行任何逻辑操作。但是,这里要注意第二个参数,这个参数允许你传递一个ID,你可以通过这个ID对其进行注入操作。除此之外,Bean内还可以存储框架内的自定义类型(class type),但前提是你必须提供一个ID。如果你有两个相同的Bean对象,那么你需要指定ID,否则后面的Bean对象将覆盖掉前面的对象。例如:

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

BeanProvider instances

BeanProvider是Bean对象的集合。BeanProvider内提供的Bean对象可以是任何类型,也包括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()];
        }
    }
}

一旦你创建了一个BeanProvider,那么你可以将以前的所有Bean对象添加进去。

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

ProtoBeans

ProtoBean可以在Bean对象创建的时候注入进去。在注入的时候你需要为ProtoBean传递一个类和一个ID。

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

Using a ProtoBean here will allow StarlingMVC to create the instances of this class for you. Each time it is injected, it will be a new instance of the, in this case, "Character" class instead of using a singleton like a normal Bean. The advantage to allowing the framework to create the class over just using "new Character()" is that when StarlingMVC creates the instance it will run injection and all processing on the created instance.

依赖注入

依赖注入可以用于所有的Bean对象和所有的Starling显示对象。实现方法可以使用元标签来实现getting/setting的方式来存取,注入的实现方法如下:

package com.mygame.controllers
{
    public class GameController
    {
        [Inject]
        public var gameModel:GameModel;
 
        public function GameModel():void
        {
 
        }
    }
}

或者指定一个ID,当你创建Bean对象的时候指定一个ID:

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

In the above example, if the GameModel is a normal bean, the framework will set the value to the singleton instance that was created during setup. If it was a protobean, a new instance will be created and injected into the property.

Starling also supports injecting properties of beans. In order to use this functionality, the source Bean must contain an id (i.e. new Bean(new GameModel(),"gameModel");). To inject a property of a bean, simply append the property name to the end of the id parameter in your Inject tag:

package com.mygame.controllers
{
    public class GameController
    {
        [Inject(source="gameModel")]
        public var gameModel:GameModel;
 
        [Inject(source="userModel.currentUser")]
        public var currentUser:User;
 
        public function GameModel():void
        {
 
        }
    }
}

In the example above, the value of the currentUser property on the userModel bean would be injected into the currentUser property of our controller. This functionality is also recursive. If you wanted to inject the first name of the currentUser you could potentially use [Inject(source="userModel.currentUser.firstName")].

Events

Dispatching Events

Events in StarlingMVC are dispatched in one of two ways: 1) StarlingMVC contains a global instance of starling.events.EventDispatcher. The quickest way to dispatch an event into the StarlingMVC framework is to use this dispatcher. This dispatcher can be injected into your bean by using the [Dispatcher] metadata tag. 2) DisplayObjects can dispatchEvents using their own dispatchEvent() method. This is only available to DisplayObjects and the events must set `bubbles=true'.

Handling Events

Event handlers are denoted by using the [EventHandler(event="")] metadata tag on a public method of a bean. The event argument in the tag can contain one of two options: the event type string

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

or the typed event

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

By using the second approach, you will gain the benefit that StarlingMVC will type check any of the events during initialization and throw and error if the event or event type doesn't exist. This protects against typos.

In both examples above, the handler must accept the type of the dispatched event to handle. However, a second optional parameter exists in the EventHandler tag that will allow you to specify specific properties of the event to use as parameters to the event handler. For example:

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

In the above example, instead of passing the entire event into the handler, StarlingMVC will pass only the "user" and "newScore" properties. Note that the types must match or an error will be thrown.

View Mediation

View mediators are a great way of keeping your view classes separate from the code that controls them. A view mediator is set up just like any other bean. To link a view to a view mediator a [ViewAdded] metadata tag is used on a public method. When a DisplayObject is added to the stack, StarlingMVC will look for instances of the ViewAdded tag. If the parameter of any ViewAdded methods are of the type of the view that was just added, the new DisplayObject will be passed to that method. To unlink a mediator from a view when the view has been removed the [ViewRemoved] metadata tag is used.

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 生命周期

Normal beans are set up on initialization. However, since the dependency injection and event handling happens after creation bean values are not available immediately. To receive notification of when a bean has been fully processed we can add the [PostConstruct] tag to a public method. This method will be automatically called when all DI has been completed. Similarly, when a bean is being destroyed we can specify a public method to be called with the [PreDestroy] tag. This works in all standard beans and DisplayObjects.

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="com.mygame.events.ScoreEvent.SCORE_CHANGED", 
properties="user, newScore")]
        public function scoreChanged(user:User, newScore:int):void
        {
 
        }
    }
}

Bean的创建/删除

通过Bean可以手动的创建和移除系统中的事件侦听。BeanEvent.ADD_BEAN会侦听系统中添加和处理一个新的Bean。BeanEvent.REMOVE_BEAN会侦听系统中移除Bean。

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

在上面的例子中,我们创建了一个演示模型,它被作为一个Bean对象添加到StarlingMVC。下面我们来看一下如何管理Bean中的事件。

EventMap

EventMap是一个用于创建和管理事件侦听器的实用工具类。使用EventMap可以很容易清理类中的监听。

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
        {
 
        }
    }
}

ViewManager

ViewManager是一个工具类,通过它可以用来在舞台上添加删除视图。当我们创建ViewManager事例的时候,我们需要传递一个根显示对象。这样我们通过ViewManager可以在Starling的任意位置方便的添加可视化交互内容。

setView

调用setView方法,将删除现有的视图,同时添加一个新的视图。ViewManager会将新的视图自动实例化并添加到堆栈中。

package com.mygame.controllers
{
    public class NavigationController
    {
        [Inject]
        public var viewManager:ViewManager;
 
        [EventHandler
(event="com.mygame.events.NavigationEvent.NAVIGATE_TO_VIEW", 
properties="viewClass")]
        public function navigateToView(viewClass:Class):void
        {
            viewManager.setView(viewClass);
        }
    }
}

添加视图

调用addView方法将在现有视图上添加一个新的视图。这里通过addView方法将GameHUD类型的视图添加到现有视图管理器中。

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);
        }
    }
}

移除视图

通过调用removeView可以删除堆栈中制定的视图。

移除所有视图

调用removeAll可以移除堆栈中存在的所有视图。当你调用setView()的时候这个方法会被自动调用。

分享到:
评论

相关推荐

    Starling Feathers:Starling专属UI框架

    Starling Feathers是一款专为Adobe Starling框架设计的UI库,它允许开发者创建美观、高性能的2D用户界面。Starling本身是一个跨平台的游戏开发框架,基于ActionScript 3.0,利用硬件加速来实现高效的2D图形渲染,...

    <CitrusEngine系列教程二:结合starling和Box2D开发游戏>示例源码

    1. **CitrusEngine**:CitrusEngine是一个轻量级的ActionScript3游戏引擎,专为Flash平台设计,提供了一套完整的游戏开发工具和架构。它包括事件处理、状态管理、时间线动画、精灵(Sprite)管理等功能,简化了游戏...

    Starling,Features和StarlingMVC第三方库

    Starling 是一个强大的2D游戏开发框架,它基于Adobe Flash Player和Adobe AIR,为开发者提供了在这些平台上实现高性能图形渲染的能力。Starling 使用Stage3D技术,能够将2D渲染优化到接近原生代码的速度,这使得它...

    Starling框架中文教程

    - **轻量级**:Starling框架本身体积不大,约80KB的代码量,并且无需额外依赖,这有助于减少应用的内存占用和加载时间。 - **免费开源**:遵循Simplified BSD许可证发布,支持商业用途,拥有活跃的开发者社区。 #...

    框架starling

    Starling框架是一款强大的2D图形渲染引擎,专为ActionScript 3.0和Flash Player以及Adobe AIR设计。它由Daniel Sieradski开发,旨在提供一个高性能、低级别的图形接口,使得开发者能够利用硬件加速来创建复杂的2D...

    Starling框架帮助手册中文版(PDF下载).rar

    《Starling框架帮助手册中文版》是为Flash开发者准备的一份详尽指南,旨在帮助他们充分利用这个框架的优势。PDF文档中涵盖了Starling的基本概念、安装与设置、核心类库、渲染机制、性能优化以及与其他技术(如...

    基于Starling的AdobeAIRMobileApp手势识别框架_ActionScript_JavaScript_下.zip

    【标题】中的“基于Starling的AdobeAIRMobileApp手势识别框架_ActionScript_JavaScript_下.zip”表明这是一个关于使用Starling框架开发的手势识别系统,适用于Adobe AIR移动应用程序。这个框架可能结合了...

    adobe starling as3 flash 3d Starling演讲PPT以及附件

    StarlingMVC是一个为使用Starling来开发游戏的MVC框架。这个框架的特性方面,很像Swiz和RobotLegs。特性列表如下: • 依赖注入(DI)/控制反转(IOC) • 视图代理(View Mediation) • 事件捕获(Event Handling) • 非...

    StarlingFeathers:整合Starling+Feathers 还有一些Starling扩展

    #####整合Starling+Feathers 还有一些Starling扩展 #####Starling 1.7.1+ Feathers 2.0.1 Starling源码的优化 1.关闭Enterframe事件。 (1.3的包 1.4引擎自己已经优化) starling本身会每一帧遍历所有对象派发...

    starling中文API

    Starling是一个基于Adobe Flash Player和Adobe AIR的2D游戏开发框架,它利用硬件加速来提供高性能的图形渲染。这个框架由Daniel Slopianka创建,主要用于简化2D游戏的开发,尤其是在移动设备上。"Starling中文API"是...

    Starling1.5.1

    Starling的目标是为开发者提供一个简单易用、高效的平台,用于创建高质量的2D游戏和图形密集型应用,尤其适用于移动设备。标题中的"Starling1.5.1"指的是这个压缩包中包含的是Starling框架的1.5.1版本。 在描述中...

    基于starling的游戏

    Starling是一个跨平台的ActionScript 3库,它为开发者提供了硬件加速的2D图形渲染,使得在Flash Player或Adobe AIR上运行的游戏能够达到接近原生应用的性能。由于其高效性和易用性,Starling框架在HTML5时代仍受到...

    Starling中文帮助手册

    **Starling**是一个专为**ActionScript 3**(简称AS3)开发者设计的轻量级框架,其核心优势在于利用**Stage3D API**实现了硬件加速,极大地提升了2D Flash应用的性能。该框架特别适用于游戏开发领域,但其实用性远...

    starling2kashflow:将Starling银行的CSV文件转换为Kashflow可以导入的文件

    将Starling银行的CSV文件转换为Kashflow可以导入的文件 转换Starling Bank CSV格式以由Kashflow导入 动机我最近注册了Starling Bank商业帐户。 Kashflow本身并没有连接到Starling,这是一个巨大的麻烦。 尽管针对...

    Starling-Filters, 用于 Starling AS3框架的过滤器集合.zip

    Starling-Filters, 用于 Starling AS3框架的过滤器集合 starling滤波器用于与 AS3框架一起使用的过滤器集合。master 分支包含用于 Starling 2.0的过滤器。对于 Starling 1.x,使用 archive 分支中的筛选器。演示应用...

    PrimaryFeather-Starling-Framework-v1.0-5框架源码

    Starling是一个轻量级的框架,它提供了一个简单的API,使得开发者能够用类似常规2D绘图的方式去处理Stage3D。Starling的主要特点包括: 1. **硬件加速**:通过Stage3D,Starling将所有的图形操作交由GPU处理,大大...

    starling-extensions:Starling框架的扩展

    八哥延伸Starling框架的扩展更新2013.01.23 ScrollImage: 性能提升。 在构造函数中添加了参数useBaseTexture。 如果为“ true”,则Scrollimage将使用整个纹理区域(没有UV剪切,纹理必须是两倍大小的幂)。 此设置...

    Starling演讲PPT以及附件

    Starling是Adobe Flash平台上的一款高性能2D游戏和图形渲染框架,它允许开发者使用ActionScript 3.0创建复杂的、互动的、低延迟的2D应用,尤其适合开发游戏。这个"Starling演讲PPT以及附件"的压缩包很可能包含了一场...

    Starling Graphics extension 绘图API 扩展

    总的来说,Starling Graphics扩展是Starling框架的重要补充,它为开发者提供了强大的绘图工具,使得在移动平台上创建高质量的2D游戏和应用变得更加便捷。无论你是新手还是经验丰富的开发者,都应该了解并掌握这一...

Global site tag (gtag.js) - Google Analytics