2013-07-01 103 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。 –