Cairngorm中各层的含义与关系参见《Cairngorm框架——MVC基本理论》,这里探讨一下View层的交互问题。
根据Cairngorm的原理,View层中的数据通过绑定ModelLocator中的属性实现自动更新,但有时我们想要的效果不仅仅是数据自动更新这么简单,而且有可能会对View层界面进行操作,譬如切换状态、弹出提示窗口、弹出选择界面等,这些操作如果放在Command中处理的话,使Controller层与View层耦合了,不利于MVC松散耦合的概念。
举个简单例子
Flex程序由两个界面组成:登陆界面和主界面,在Application中分别定义为login和main状态,默认为login状态。当login成功后,切换为main状态。
按照Cairngorm的用户登陆Command如下:
import com.adobe.cairngorm.commands.ICommand;
import com.adobe.cairngorm.control.CairngormEvent;
import mx.controls.Alert;
import mx.core.FlexGlobals;
import mx.rpc.IResponder;
import spark.components.Application;
public class UserLoginCommand implements ICommand, IResponder
{
public function execute(event:CairngormEvent):void
{
var e:UserLoginEvent = event as UserLoginEvent;
var delegate:SystemDelegate = new SystemDelegate(this);
delegate.userLogin(e.userName, e.password);
}
public function result(data:Object):void
{
var app:Application = (FlexGlobals.topLevelApplication) as Application;
app.currentState = "main";
}
public function fault(info:Object):void
{
Alert.show(info.toString());
}
}
这里,Command的代码中牵涉到Application的CurrentState了,且还有Alert.show方法,这些应该都是View层做的事情。为了达到松散耦合的墓地,我们定义一用户登陆完成事件,在Command中执行完后派发,在View层中监听该事件并处理。
定义用户登陆完成事件UserLoginCompleteEvent
import com.adobe.cairngorm.control.CairngormEvent;
public class UserLoginCompleteEvent extends CairngormEvent
{
static public const EVENT_ID:String = "userLoginComplete";
public var success:Boolean = false;
public function UserLoginCompleteEvent()
{
super(EVENT_ID);
}
}
Command代码修改为响应时向外派发UserLoginCompleteEvent事件
import com.adobe.cairngorm.commands.ICommand;
import com.adobe.cairngorm.control.CairngormEvent;
import com.adobe.cairngorm.control.CairngormEventDispatcher;
import mx.rpc.IResponder;
public class UserLoginCommand implements ICommand, IResponder
{
public function execute(event:CairngormEvent):void
{
var e:UserLoginEvent = event as UserLoginEvent;
var delegate:SystemDelegate = new SystemDelegate(this);
delegate.userLogin(e.userName, e.password);
}
public function result(data:Object):void
{
complete(true, null);
}
public function fault(info:Object):void
{
complete(false, info);
}
private function complete(success:Boolean, data:Object):void
{
var e:UserLoginCompleteEvent = new UserLoginCompleteEvent();
e.success = success;
e.data = data;
CairngormEventDispatcher.getInstance().dispatchEvent(e);
}
}
Application的creationComplete事件中监听UserLoginCompleteEvent事件
protected function creationCompleteHandler(event:FlexEvent):void
{
CairngormEventDispatcher.getInstance().addEventListener(UserLoginCompleteEvent.EVENT_ID, userLoginCompleteHandler);
}
private function userLoginCompleteHandler(e:UserLoginCompleteEvent):void
{
if (e.success)
currentState = "desktop";
else
Alert.show(e.data.toString());
}
值得注意的是,UserLoginCompleteEvent不需要在FrontController中注册,而且需要View层互动时才需要使用对应逻辑的CompleteEvent,其他互动用Cairngorm提倡的Bindable Model Locator解决。
虽然Cairngorm的代码量不少,但我个人觉得分层还是很明确的,特别是团队开发时只需要专注自己关心的部分就可以了。