【问题标题】:Best practice adding KeyMaps to a Viewport将 KeyMaps 添加到视口的最佳实践
【发布时间】:2014-12-13 21:11:11
【问题描述】:

创建/绑定 KeyMap 到视口的最佳位置是什么?

给定一个像这样的非常简单的视口:

Ext.define('EmptyTemplate.view.Viewport', {
    extend: 'Ext.container.Viewport',
    requires:[
        'Ext.layout.container.Fit',
        'EmptyTemplate.view.Main'
    ],
    layout: {
        type: 'fit'
    },

    items: [{
        xtype: 'app-main'
    }],

    listeners: {
        afterrender: {
            fn: function(){
                // map one key by key code
                this.keyMap = Ext.create('Ext.util.KeyMap', this.el, {
                    scope: this,
                    key: Ext.EventObject.ENTER,
                    fn: function () {
                        console.log("enter pressed");
                    }
                });
            }
        }
    }
});

创建 KeyMap 的正确方法是什么?

【问题讨论】:

    标签: extjs extjs4 extjs4.1


    【解决方案1】:

    首先提供一些最佳实践建议:

    如果你需要设置你的组件使用

    • [initComponent][1](您应该read this了解详细信息),
    • 另一个提供template methods
    • 在极少数情况下constructor

    在你的情况下,我会使用模板方法 afterRender

    Ext.define('EmptyTemplate.view.Viewport', {
        extend: 'Ext.container.Viewport',
        requires:[
            'Ext.layout.container.Fit',
            'EmptyTemplate.view.Main'
        ],
        layout: {
            type: 'fit'
        },
    
        items: [{
            xtype: 'app-main'
        }],
    
        afterRender: {
            this.callParent(arguments); // always!!
            this.bindKeyMap();
        },
    
        bindKeyMap: function() {
            var me = this; // use 'me' if 'this' occurs more then 3 times
            if(me.keyMap) {
                me.keyMap.enable();
                return;
            }
            // map one key by key code
            me.keyMap = Ext.create('Ext.util.KeyMap', me.el, {
                scope: me,
                key: Ext.EventObject.ENTER,
                fn: me.onEnter
            });
        },
    
        unbindKeyMap: function() {
            this.keyMap.disable();
        },
    
        onDisable: function() {
            this.unbindKeyMap();
            this.callParent(arguments); // always!!
        },
    
        onEnable: function() {
            this.callParent(arguments); // always!!
            this.bindKeyMap();
        },
    
        onEnter: function(){
           // i am executed in the scope of the class instance
        }
    });
    

    请注意,上面的示例处理整个键映射,但您也可以从映射中add / remove 单个键。

    注意这是未经测试的原型代码,但它应该可以这样工作。


    如何找到模板方法

    1. 转到docs
    2. 显示受保护的成员

    1. 寻找 标记

    This post about overriding 也可能是个好读物

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-12
      • 2019-04-08
      • 2019-03-10
      相关资源
      最近更新 更多