首页 技术 正文
技术 2022年11月20日
0 收藏 895 点赞 2,477 浏览 1730 个字

      这篇博客我们继续讲解PureMVC的三大核心类(View/Controller/Model)——Controller类。根据PureMVC模块设计,Controller类保存所有的Command映射,它的构造函数和工厂函数与View类的很相似:

function Controller(key)
{
if(Controller.instanceMap[key] != null)
{
throw new Error(Controller.MULTITON_MSG);
} this.multitonKey= key;
Controller.instanceMap[this.multitonKey]= this;
this.commandMap= new Array();
this.initializeController();
}

Controller构造函数中调用了initializeController()方法,它是用来初始化Controller对象。

Controller.prototype.initializeController= function()
{
this.view= View.getInstance(this.multitonKey);
};

initializeController()方法主要是为view属性赋值,方便调用View类的一些方法。

Controller类相对于View类的mediatorMap属性,它有一个commandMap属性,用来保存所有的Command映射,实际上所谓的映射就是一个notification对象和Command类关联在一起,形成key-value组合形式,存放在commandMap中。

那在Controller类是怎么把notification对象和Command类关联在一起的呢?它提供了一个registerCommand方法。

Controller.prototype.registerCommand= function(notificationName, commandClassRef)
{
if(this.commandMap[notificationName] == null)
{
this.view.registerObserver(notificationName, new Observer(this.executeCommand, this));
} this.commandMap[notificationName]= commandClassRef;
};

这个函数就调用了view类的registerObserver方法,通过registerObserver方法的参数,我们可以知道,当Model类接受到消息会调用executeCommand()方法,我们看看executeCommand()方法执行了哪些操作:

Controller.prototype.executeCommand= function(note)
{
var commandClassRef= this.commandMap[note.getName()];
if(commandClassRef == null)
return;
//实例化一个Command对象(SimpleCommand或者MacroCommand)
var commandInstance= new commandClassRef();
commandInstance.initializeNotifier(this.multitonKey);
//执行Command的execute方法
commandInstance.execute(note);
};

executeCommand()方法告诉我们, Command对象(SimpleCommand或者MacroCommand)是无状态的;只有在需要的时候(Controller收到相应的Notification)才会被创建,并且被执行(调用execute方法)。

Controller类还有removeCommand()/hasCommand()/removeController等方法,这些方法都很简单,建议读者自己阅读源代码,加深印象。

最后,附一张Controller类的思维导图:

PureMVC(JS版)源码解析(十):Controller类

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,078
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,553
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,402
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,177
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,814
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898