2013-07-01 102 views
1

我有一个面板,我使用下面的代码呈现。Extjs面板。键盘事件

new Ext.Panel({ 
    id: 'textPanel', 
    height: 1000, 
    width: 1200, 
    renderTo: Ext.getBody(), 
    html:"An HTML fragment, or a DomHelper specification to use as the layout element content. The HTML content is added after the component is rendered, so the document will not contain this HTML at the time the render event is fired. This content is inserted into the body before any configured contentEl is appended." 
}); 

然后我想在按下回车键时收听事件。所以,我创建一个KeyMap如下...

var map = new Ext.KeyMap(Ext.getCmp('textPanel').body, { 
    key: Ext.EventObject.ENTER, 
    fn: onKeyPress, 
    // handler: onKeyPress, 
    scope: this 
}); 

但onKeyPress函数没有被调用。

我一直在使用的

Ext.getCmp('textPanel').body.dom, 
Ext.getCmp('textPanel').el.dom, 
Ext.getCmp('textPanel').el 

代替

Ext.getCmp('textPanel').body 

没有成功已经尝试过。

如果我在那里使用“文档”,那么会调用onKeyPress函数。即

var map = new Ext.KeyMap(document, { 
    key: Ext.EventObject.ENTER, 
    fn: onKeyPress, 
    // handler: onKeyPress, 
    scope: this 
}); 

这很好,但我不想听整个文档。 我怎样才能听到面板?

+0

你是什么意思“听面板”吗?你的面板应该是'TextField'吗?在一个普通的“Ext.Panel”上听一个关键事件是没有意义的...... – kevhender

+0

我的面板在它的主体中有文本。我想在面板的主体内按下输入或制表键时做一些事情。 –

回答

2

在ExtJS的3.4,如果你想使用KeyMap那么你需要首先将焦点设置在面板元件上,否则关键事件将永远因此你将无法听到面板上的重要事件(这就是为什么你只能在文档上听重要事件的原因)

但是在extjs中没有任何方法可以将焦点设置在面板上,所以因此您需要创建一个自定义面板类来设置焦点s到本身并听取关键事件

Ext.namespace('Saket'); 

Saket.FocusPanel = Ext.extend(Ext.Panel, { 
    onRender : function() 
    { 
     Saket.FocusPanel.superclass.onRender.apply(this, arguments); 

     // this element allows the Window to be focused for keyboard events 
     this.focusEl = this.el.createChild({ 
        tag: 'a', href:'#', cls:'x-dlg-focus', 
        tabIndex:'-1', html: ' '}); 
     this.focusEl.swallowEvent('click', true); 

     this.getEl().on({ 
      click : this.focus, 
      scope : this 
     }); 
    }, 
    focus : function() 
    { 
     this.focusEl.focus(); 
    }  
}); 

new Saket.FocusPanel({ 
    id: 'textPanel', 
    height: 200, 
    width: 300, 
    renderTo: Ext.getBody(), 
    html:"An HTML fragment, or a DomHelper specification to use as the layout element content. The HTML content is added after the component is rendered, so the document will not contain this HTML at the time the render event is fired. This content is inserted into the body before any configured contentEl is appended.", 
    keys: { 
     key: Ext.EventObject.ENTER, 
     fn: function() {alert('bingo');}, 
     scope: this 
    } 
}); 

演示:http://jsfiddle.net/silentsakky/PdyqW/3/

+0

感谢您的回答,这从概念上解释了为什么我无法捕捉面板上的事件。 –

0

使用getEl()添加侦听​​面板的元素:

Ext.getCmp('textPanel').getEl().on('keydown', function(f, e) { 
    if (e.getKey() === Ext.EventObject.ENTER) 
    { 
     //do whatever you want here 
    } 
}); 
+1

不起作用。该功能从未被调用过。 –

+0

您使用的是什么版本的ExtJS?这对4.1.3和4.2.1有帮助。 – kevhender

+0

我正在使用extjs 3.4。 –