您的位置:首页 > Web前端 > JavaScript

如何使用javascript的PureMVC框架 - Command/controller层

2012-07-02 14:42 561 查看
本实例的最终源文件下载地址

http://download.csdn.net/detail/laogong5i0/4400288

相关教程:
如何使用javascript的PureMVC框架 - Mediator/View层

继续上次 如何使用javascript的PureMVC框架 - 初始化 后我们在来看看command是如何使用的

Controller保存所有Command的映射。Command类是无状态的,只在需要时才被创建。

Command是负责处理复杂的数据逻辑的地方,它的使用归纳起来有两种

1. 通过发送Notification 来触发Command

2. addSubCommand() 来启动

口水不要太多,我们马上进入正题

在demo文件夹下建立文件夹controller ,然后在controller夹下建立一个叫StartupCommand.js的js文件,输入以下内容

var StartupCommand = Objs("sweeps.controller.StartupCommand",
MacroCommand,
{
/**
* @override
* 添加Subcommands来启动PuerMVC组件
* 通常这里是先准备Model(即Proxy),然后是View(即Mediators);
*/
initializeMacroCommand: function( note )
{
alert('收到由facade发来的');
//this.addSubCommand( PrepModelCommand );
//this.addSubCommand( PrepViewCommand );
}

});

跟着在demo文件夹下面建立一个文件夹abc来存放Noticefiction,在abc文件夹下建立NotificationNames.js文件,输入下面内容

var NotificationNames = Objs("demo.abc.NotificationNames",{});

NotificationNames.STARTUP = "startup";


然后在html文件里导入 StartupCommand.js和NotificationNames.js文件

<script type="text/javascript" src="src/demo/abc/NotificationNames.js"></script>
<script type="text/javascript" src="src/demo/controller/StartupCommand.js"></script>

完成后程序的目录树为下图



跟着回到上次如何使用javascript的PureMVC框架 - 初始化里面的 ApplicationFacade.js类

在 initializeController()方法里面添加代码

ApplicationFacade.$super.initializeController.call( this );
//注册StartupCommand,并让他监听STARTUP消息
this.registerCommand( NotificationNames.STARTUP, StartupCommand );




以及在startup()方法里面添加代码

//发送STARTUP消息给StartupCommand
this.sendNotification( NotificationNames.STARTUP, app );
这里主要是通过使用sendNotification(notice, app);方法发送Notification来触发StartupCommand 类。

程序在初始化的时候调用initializeController()方法,并使用registerCommand()方法注册了StartupCommand实例,

这样当收到由sendNotification()方法发送出来的NotificationNames.STARTUP消息后就会触发StartupCommand实例的initializeMacroCommand()方法了

运行后你会看到“收到由facade发来的”。

接下来我们来看看怎么使用addSubCommand() 来启动Command实例.

现在controller文件夹下新建PrepViewCommand.js文件,并输入以下内容

var PrepViewCommand = Objs("demo.controller.PrepViewCommand",
SimpleCommand,
{
/**
* @override
*/
execute: function( note )
{
alert('使用addSubCommand方法调用Command实例');
}
});
然后在html文件里导入 PrepViewCommand.js文件。

<script type="text/javascript" src="src/demo/controller/PrepViewCommand.js"></script>
接着在StartupCommand.js文件的initializeMacroCommand方法添加

this.addSubCommand( PrepViewCommand );
这样就可以调用到PrepViewCommand.js文件的execut()方法了!

运行看是不是有输出?

最后文件夹目录树为



本实例的最终源文件下载地址

http://download.csdn.net/detail/laogong5i0/4400288




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: