Sencha的MVC模式实践


Sencha Touch中,Application对象表示整个Sencha的应用程序。对于大多数程序而言,它至少包括有应用程序的名称和一个启动函数:

new Ext.Application({
    name: 'MyApp',
    launch: function() {
        this.viewport = new Ext.Panel({
            fullscreen: true,
            
            id    : 'mainPanel',
            layout: 'card',
            items : [
                {
                    html: '欢迎来到我们的程序!Welcome to My App!'
                }
            ]
        });
    }
});

实例化新的程序的时候,会自动依据配置项name来定义一个全局变量,设置程序的命名空间,包括有视图的命名空间、store的命名空间和控制器的命名空间。

// 当创建程序就是定义下面的代码
// 与Ext.ns的作用一致
('MyApp', 'MyApp.views', 'MyApp.stores', 'MyApp.models', 'MyApp.controllers');

启动函数其职责一般是创建应用程序的Viewport视图和任何程序需要启动的步骤。启动函数应该只会运行一次。
路由与历史的支持 Routes and history support

Ext应用程序提供紧密的关联与历史的支持,允许你的用户在应用程序中,既可以使用“后退”按钮,也可以“刷新”页面,哪怕关闭回来后相同的屏幕。紧密的历史回溯依靠路由引擎(Routing Engine)的支持,将url映射到controller/action。这里是一个定义路由的例子:

//Note the # in the url examples below
Ext.Router.draw(function(map) {
    //maps the url http://mydomain.com/#dashboard to the home controller's index action
    map.connect('dashboard', {controller: 'home', action: 'index'});
    //fallback route - would match routes like http://mydomain.com/#users/list to the 'users' controller's
    //'list' action
    map.connect(':controller/:action');
});

如果你透过Sencha Command工具生成脚本来导出Sencha程序,那么将会看到这个文件已经位于程序目录的app/routes.js。历史驱动可以指定defaultUrl 配置项,在当前没有设置url的情况下派遣到默认的url。

new Ext.Application({
    name: 'MyApp',
    defaultUrl: 'dashboard'
});

Application profiles
Applications支持为程序提供多个profiles并且可以依据此自配置。这里我们设置了Application的三个profile,一个是手机上的,另外两个是table PC的landscape和portrait方向。

new Ext.Application({
    name: 'MyApp',
    profiles: {
        phone: function() {
            return Ext.is.Phone;
        },
        tabletPortrait: function() {
            return Ext.is.Tablet && Ext.orientation == 'portrait';
        },
        tabletLandscape: function() {
            return Ext.is.Tablet && Ext.orientation == 'landscape';
        }
    }
});

当Application 检查其prfile的列表时候,第一个返回true的那个函数表示就是当前的函数。当profile发生变化时,Application会自动检测哪一个 profile使用(比如,在tablet方向从portrait变为landscape模式的时候),并触发profilechange事件。同时也会通知页面上所有的 Ext.Component已经改变了当前的profile,进而调用组件的setProfile()函数。setProfile函数一个空函数,你可以为你的组件在交互不同设备写入新的实现。API中可通过getProfile()获取当前的profile。如果Application没有成功检测 profile发生则改变可以手动执行determineProfile() 。

原文作者: frank
转自:http://blog.csdn.net/zhangxin09/archive/2011/01/05/6118480.aspx