PureMVC(JS版)源码解析(十):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();
}

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类的思维导图:

原文地址:https://www.cnblogs.com/iRavior/p/3363107.html