extjs-mvc构造实践(四):导航菜单与控制器模块联动

前面几篇文档,我们基础完成了一个静态的extjs页面,本篇最先,完成左边导航树与右边内容的联动,也就是点击导航菜单,加载对应模块页面和营业逻辑,完成js文件的按需加载。

营业需求是如许的:

左边的treelist,当点击某个节点的时刻,体系依据tree数据里设置的模块信息,加载这个模块,而且把模块对应的主页面显现在中心地区的tabpanel里。

革新主控制器:app/luter/controller/MainController.js

监听导航树的node点击事宜,举行后续处置惩罚:

 'navlist': {
    'itemclick':function(el, record, opt){
        //能够经由历程以下体式格局猎取点击节点的数据。
        var nodeData = record.node.data;
    
    }
}

完全的代码以下:


Ext.define('luter.controller.MainController', {
    extend: 'Ext.app.Controller',
    views: ['main.ViewPort'],
    stores: ['NavTreeStore'],
    init: function (application) {
        var me = this;
        this.control({
            'viewport': {//监听viewport的初始化事宜,能够做点其他事变在这里,若有必要,记得viewport定义里的alias么?
                'beforerender': function () {
                    console.log('viewport begin render at:' + new Date());
                },
                'afterrender': function () {
                    console.log('viewport  render finished at:' + new Date());
                },
            },
            'syscontentpanel': {
                'afterrender': function (view) {
                    console.log('syscontentpanel rendered at:' + new Date());
                }
            },
            'navlist': {
                'itemclick': function (el, record, opt) {
                    var nodeData = record.node.data;//当前点击节点的数据

                    var tabpanel = Ext.getCmp('systabpanel');//中心tabpanel
                    var tabcount = tabpanel.items.getCount();//当前tabpanel已翻开几个tab了。
                    var maxTabCount = 5;//最大翻开的tab个数
                    if (tabcount && tabcount > 5) {
                        showFailMesg({
                            title: '为了更好的运用,最多许可翻开5个页面',
                            msg: '您翻开的页面过量,请关掉一些!'
                        });
                        return false;
                    }
                    if (nodeData.leaf) {//是翻开新模块,否则是睁开树节点
                        var moduleID = nodeData.module_id;//找到控制器ID,定义在tree的数据里modole_id
                        if (!moduleID || moduleID == '') {
                            showFailMesg({
                                title: '建立模块失利.',
                                msg: '模块加载毛病,模块id为空,建立模块失利'
                            });
                            return false;
                        }
                        console.log('to add module with id:' + moduleID);
                        //最先加载控制器
                        try {
                           //尝试加载这个控制器,这个历程就是按需ajax加载js文件的历程。
                          //假如这个模块被加载过,则不会反复加载。
                            var module = luterapp.getController(moduleID);
                        } catch (error) {
                            showFailMesg({
                                msg: '依据模块ID:' + moduleID + '建立模块失利。' +
                                '<br> 能够的缘由 :<br>1、该模块当前没有完成.' +
                                '<br> 2、模块文件称号与模块称号不一致,请搜检' +
                                '</br><span style="color: red">Error: ' + error + '</span>'
                            });
                            return false;
                        } finally {

                        }
                        //推断模块是不是加载下来,由于是ajax加载,所以照样推断一下比较好
                        if (!module) {
                            showFailMesg({
                                msg: 'B:load module fail,the module object is null.' +
                                '<br> maybe :the module is Not available now.'
                            });
                            return false;

                        }
                        //加载到以后,默许去猎取控制器里views:[]数组里的第一个作为主视图
                        var viewName = module.views[0];
                        console.log('will create a tab with view ,id:' + viewName);
                        var view = module.getView(viewName);
                        console.log('get the view el:' + view);
                        if (!view) {
                            showFailMesg({
                                msg: 'Sorry ,to get the module view fail...'
                            });
                            return false;
                        }

                        //推断一下这个视图是不是是已加载到tabpanel里去了
                        var tabid = me.getTabId(moduleID);
                        console.log('will create a tab with id:' + tabid);
                        var notab = tabpanel.getComponent(tabid);
                        var viewEL = view.create();
                        if (!viewEL) {
                            showFailMesg({
                                msg: 'Sorry ,to get the module viewEL fail...'
                            });
                            return false;
                        }

                        if (!notab && null == notab) {//不存在新建
                            //不管是啥,都放到一个panel内里。
                            notab = tabpanel.add(Ext.create('Ext.panel.Panel', {
                                tooltip: nodeData.text + ':' + nodeData.qtip,
                                id: tabid, // tab的唯一id
                                title: nodeData.text, // tab的题目
                                layout: 'fit', // 添补规划,它不会让load进来的东西转变大小
                                border: false, // 无边框
                                closable: true, // 有封闭选项卡按钮
                                iconCls: nodeData.iconCls,
                                listeners: {
                                    // 侦听tab页被激活里触发的行动
                                    scope: this,
                                    destroy: function () {
                                        console.log("tab :" + tabid + ",has been destroyed")
                                    }
                                },
                                items: [view.create()]
                            }));
                            //新建以后focus
                            tabpanel.setActiveTab(notab);
                        }
                        else {//假如这个tab已存在了,则focus到这个tab
                            tabpanel.setActiveTab(notab);
                        }
                    } else {
                    //假如leaf  =false,则申明这不是一个最底层节点,是目次,睁开。
                        console.log('tree node expand')
                    }
                }
            }
        });
    },
    //这个要领从tab id里星散出控制器称号
    getTabId: function (mid) {
        var winid = mid;
        var c = winid.split('.');
        winid = c.pop();
        return winid + '-tab';
    }

});

左边菜单树对应的测试数据:app/testdata/menu.json

平常状况下,这个菜单数据是保留在后端的,经由历程权限推断加载用户可接见的资本构成树构造返回给前端运用。leaf标清楚明了这是一个目次照样一个模块,module_id对应的是控制器的途径。 比以下面这个测试数据中。 “leaf”: true, “module_id”: “sys.UserController”, 在app.js中,我们设置了appFolder:‘app/luter’, leaf标清楚明了这是一个控制器模块,点击后会去触发控制器加载行动。 所以这个模块的现实途径(也就是js文件)就是:${appFolder}/controller/${module_id}.js 即:app/luter/controller/sys.UserController.js

 [
  {
    "id": "111",
    "text": "体系治理",
    "href": null,
    "leaf": false,
    "iconCls": "fa fa-home",
    "module_id": "no sign",
    "qtip": "这个处所显现鼠标悬停提醒",
    "children": [
      {
        "id": "11111",
        "text": "用户治理",
        "href": null,
        "leaf": true,
        "iconCls": "fa fa-user",
        "module_id": "sys.UserController",
        "qtip": "体系用户治理",
        "children": []
      }
    ]
  }

]

导航菜单与tabpanel 联动完成,下面弄个控制器试验一下结果,以新建一个体系治理分类下的用户治理模块功能为例:
体系治理部份模块放在sys目次下,so:

  • 控制器:app/luter/controller/sys/UserController.js
  • 模子:app/luter/model/UserModel.js
  • Store:app/luter/store/UserStore.js
  • 视图主进口:app/luter/model/view/sys/user/User.js
  • 列表视图:app/luter/model/view/sys/user/UserList.js
  • ……

用户治理控制器 :app/luter/controller/sys/UserController.js


Ext.define('luter.controller.sys.UserController', {
    extend: 'Ext.app.Controller',
    stores: ['UserStore'], //用户store
    views: ['sys.user.User'], //主view ,tab里会加载第一个视图。
    init: function () {
        this.control({
            'userlistview': {
                'beforerender': function (view) {
                    console.log("beforerender   list......   ");
                },
                'afterrender': function (view) {
                    console.log("afterrender   list......   ");
                     // this.getUserStoreStore().load();//假如UserStore里没设置autoLoad: true,就能够在这里加载用户数据
                }
            }
        });

    }
});

用户模子Model:app/luter/model/UserModel.js


Ext.define('luter.model.UserModel', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'id', type: 'string'},
        {name: 'username', type: 'string'},
        {name: 'gender', type: 'string'},
        {name: 'real_name', type: 'string'}
    ]
});

用户Store:app/luter/store/UserStore.js


Ext.define('luter.store.UserStore', {
    extend: 'Ext.data.Store',
    autoLoad: true,//自动加载数据
    model: 'luter.model.UserModel',//运用的模子
    pageSize: 15,//每页数据若干
    proxy: {
        type: 'ajax',//ajax猎取数据
        actionMethods: {
            create: 'POST',
            read: 'POST',
            update: 'POST',
            destroy: 'POST'
        },
        api: {
            read: 'app/testdata/user.json'//从这个处所猎取数据,固然,这里用测试数据
        },
        reader: {//返回数据解析器
            type: 'json',
            root: 'root',//用户列表数据在这个字段下
            successProperty: 'success',//胜利与失利的标志位是这个字段
            totalProperty: 'total'//纪录总数在这个字段
        },
        listeners: {
            exception: function (proxy, response, operation, eOpts) {
                DealAjaxResponse(response);//监听ajax非常提醒毛病
            }
        }
    },
    remoteSort: true,//服务器端排序
    sortOnLoad: true,//加载就排序
    sorters: {//拿ID排序
        property: 'id',
        direction: 'DESC'
    }

});

用户治理模块主视图:app/luter/model/view/sys/user/User.js

Ext.define('luter.view.sys.user.User', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.userview',
    layout: 'fit',
    requires: ['luter.view.sys.user.UserList'],//引入用户列表模块
    border: false,
    initComponent: function () {
        var me = this;
        me.items = [{
            xtype: 'userlistview',
            layout: 'fit'

        }]
        me.callParent(arguments);
    }
});

用户列表视图:app/luter/model/view/sys/user/UserList.js

Ext.define('luter.view.sys.user.UserList', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.userlistview',//其他处所就能够这么用:xtype:‘userlistview’
    requires: [],
    store: 'UserStore',//用到的store
    itemId: 'userGrid',//本身的itemid
    columnLines: true,//是不是显现表格线
    viewConfig: {
        emptyText: '<b>暂无数据</b>'//store没数据的时刻显现这个
    },
    initComponent: function () {
        var me = this;
        me.columns = [{
            xtype: 'rownumberer',
            text: '序号',
            width: 60
        }, {
            header: "操纵",
            xtype: "actioncolumn",
            width: 60,
            sortable: false,
            items: [{
                text: "删除",
                iconCls: 'icon-delete',
                tooltip: "删除这条纪录",
                handler: function (grid, rowIndex, colIndex) {
                    var record = grid.getStore().getAt(rowIndex);
                    if (!record) {
                        toast({
                            msg: '请选中一条要删除的纪录'
                        })
                    } else {
                        showConfirmMesg({
                            message: '肯定删除这条纪录?',
                            fn: function (btn) {
                                if (btn === 'yes') {
                                    Ext.Ajax.request({
                                        url: 'sys/user/delete',
                                        method: 'POST',
                                        params: {
                                            id: record.get('id')
                                        },
                                        success: function (response, options) {
                                            DealAjaxResponse(response);
                                            Ext.data.StoreManager.lookup('User').load();
                                        },
                                        failure: function (response, options) {
                                            DealAjaxResponse(response);
                                        }
                                    });
                                } else {
                                    return false;
                                }
                            }

                        })

                    }

                }
            }]
        }, {
        
            header: baseConfig.model.user.id,
            dataIndex: 'id',
            hidden: false,
            flex: 1
        },

            {
                header: baseConfig.model.user.username,
                dataIndex: 'username',
                flex: 1
            },
            {
                header: baseConfig.model.user.real_name,
                dataIndex: 'real_name',
                flex: 1
            }
        ]

        me.bbar = Ext.create('Ext.PagingToolbar', {
            store: me.store,
            displayInfo: true,
            displayMsg: '当前数据 {0} - {1} 总数: {2}',
            emptyMsg: "没数据显现",
            plugins: [new Ext.create('luter.ux.grid.PagingToolbarResizer', {
                options: [5, 10, 15, 20, 25, 50, 100]
            })]
        })
        me.dockedItems = [{
            xtype: 'toolbar',
            items: [{
                text: '增加',
                iconCls: baseConfig.appicon.add,
                tooltip: '增加',
                handler: function () {
                    var win = Ext.create('luter.view.sys.user.UserAdd');
                    win.loadView();
                    win.show();

                }
            }]
        }]
        me.listeners = {
            'itemdblclick': function (table, record, html, row, event, opt) {
                if (record) {
                    var id = record.get('id');
                    var view = Ext.create('luter.view.sys.user.UserEdit', {title: '编辑数据'});
                    view.loadView();
                    loadFormDataFromDb(view, 'sys/user/view?id=' + id);
                } else {
                    showFailMesg({
                        msg: '加载信息失利,请确认。'
                    })
                }

            }
        }
        me.plugins = []
        me.callParent(arguments);
    }
});

//这里的baseConfig定义在大众设置文件config.js中,以下:

大众设置参数定义文件:app/luter/config.js

别忘记在app.html中app.js之前引入这个文件。


/**
 * icon_prefix font字体前缀定义
 * baseConfig 全局设置
 */
var icon_prefix = " fa blue-color ", baseConfig = {
    /**
     * 全局常量定义
     */
    cons: {
        noimage: 'app/resource/images/noimage.jpg',
        /**
         * 静态服务器的地点
         */
        static_server: ''
    },
    /**
     * 衬着器,对Boolean范例的表格列的显现内容举行衬着
     */
    renders: {
        trueText: '<i   class=" fa fa-lg fa-check green-color"></i>',
        falseText: '<i   class=" fa fa-lg fa-close red-color"></i>',
        cancel: '<i class=" fa fa-lg fa-undo"></i>'
    },
    /**
     * 图标定义
     */
    appicon: {
        home: icon_prefix + 'fa-home',
        add: icon_prefix + "fa-plus",
        update: icon_prefix + "fa-edit",
        trash: icon_prefix + "fa-trash",
        delete: icon_prefix + "fa-remove red-color",
        set_wallpaper: icon_prefix + "fa-image",
        setting: icon_prefix + "fa-gears",
        desktop: icon_prefix + "fa-desktop",
        pailie: icon_prefix + "fa-cubes",
        logout: icon_prefix + "fa-power-off",
        avatar: icon_prefix + "fa-photo",
        key: icon_prefix + "fa-key",
        user: icon_prefix + "fa-user",
        refresh: icon_prefix + "fa-refresh blue-color",
        close: icon_prefix + "fa-close",
        male: icon_prefix + 'fa-male',
        female: icon_prefix + 'fa-female',
        role: icon_prefix + 'fa-users',
        user_add: icon_prefix + "fa-user-plus",
        undo: icon_prefix + 'fa-undo',
        search: icon_prefix + 'fa-search',
        reset: icon_prefix + 'fa-retweet',
        yes: icon_prefix + 'fa-check green-color',
        no: icon_prefix + 'fa-close red-color',
        list_ol: icon_prefix + ' fa-list-ol',
        list_alt: icon_prefix + ' fa-list-alt',
        ban: icon_prefix + "fa-ban",
        log: icon_prefix + "fa-tty",
        printer: icon_prefix + "fa-print",
        fax: icon_prefix + "fa-fax",
        download: icon_prefix + "fa-cloud-download",
        upload: icon_prefix + "fa-cloud-upload",
        comment: icon_prefix + " fa-commenting-o",
        credit: icon_prefix + "fa fa-gift"
    },
    /**
     * 模子定义
     */
    model: {
        /**
         * 体系用户模子
         */
        user: {
            id: 'ID',
            username: '用户名',
            real_name: '实在姓名'
        }
    }
};

末了,附上用户列表的测试数据(固然,瞎编的……):app/testdata/user.json

{
  "total": 33,
  "root": [
    {
      "id": "aaa",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "ccc",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "ddd",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "eee",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    },
    {
      "id": "fff",
      "username": "user",
      "real_name": "用户"
    }
  ],
  "success": true
}

如上,没问题的话,革新页面,应该能看到以下所示:

《extjs-mvc构造实践(四):导航菜单与控制器模块联动》

上图中,一些Extjs默许的款式经过了hack。不是默许款式。
终究,全部项目的目次构造以下:
《extjs-mvc构造实践(四):导航菜单与控制器模块联动》

推断是不是是动态按需加载?

1、翻开chrome的开辟控制台,切换到network面板的js下。
2、革新页面
3、反复点击左边用户治理,检察JS加载状况。一般状况下同一个模块的js只加载一次。

    原文作者:差点笨死
    原文地址: https://segmentfault.com/a/1190000012941478
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞