PureMVC(JS版)源码解析10:Controller类
  
这篇文章讲解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();
}
 2
3
4
5
6
7
8
9
10
11
12
13
Controller构造函数中调用了initializeController()方法,它是用来初始化Controller对象。
Controller.prototype.initializeController= function()
{
    this.view= View.getInstance(this.multitonKey);
};
 2
3
4
5
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;
};
 2
3
4
5
6
7
8
9
10
这个函数就调用了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);
};
 2
3
4
5
6
7
8
9
10
11
12
executeCommand()方法告诉我们,Command对象(SimpleCommand或者MacroCommand)是无状态的;只有在需要的时候(Controller收到相应的Notification)才会被创建,并且被执行(调用execute()方法)。
Controller类还有removeCommand()/hasCommand()/removeController()等方法,这些方法都很简单,建议读者自己阅读源代码,加深印象。