事件监听
添加监听处理
声明式
Ext.create('Ext.Panel', {
html: 'My Panel',
renderTo: Ext.getBody(),
listeners: {
afterrender: function() {
Ext.Msg.alert('Success!', 'We have been rendered');
}
}
});
延后式
var button = Ext.create('Ext.Button', {
renderTo: Ext.getBody(),
text: 'My Button'
});
button.on('click', function() {
Ext.Msg.alert('Success!', 'Event listener attached by .on');
});
移除监听处理
var doSomething = function() {
Ext.Msg.alert('Success!', 'listener called');
};
var button = Ext.create('Ext.Button', {
renderTo: Ext.getBody(),
text: 'My Button',
listeners: {
click: doSomething,
}
});
Ext.defer(function() {
button.un('click', doSomething);
}, 3000);
作用域
var panel = Ext.create('Ext.Panel', {
html: 'Panel HTML'
});
var button = Ext.create('Ext.Button', {
renderTo: Ext.getBody(),
text: 'Click Me'
});
// 每个监听处理使用相同的作用域
button.on({
click: function() {
Ext.Msg.alert('Success!', this.getXType());
},
scope: panel
});
// 每个监听处理可以有不同的作用域
button.on({
click: {
scope: panel,
fn: function() {
Ext.Msg.alert('Success!', this.getXType());
}
}
});
只监听一次
var button = Ext.create('Ext.Button', {
renderTo: Ext.getBody(),
text: 'Click Me',
listeners: {
click: {
single: true,
fn: function() {
Ext.Msg.alert('Success!', 'I will say this only once');
}
}
}
});
事件缓冲
var button = Ext.create('Ext.Button', {
renderTo: Ext.getBody(),
text: 'Click Me',
listeners: {
click: {
buffer: 2000, // 缓冲 2 秒
fn: function() {
Ext.Msg.alert('Success!', 'I say this only once every 2 seconds');
}
}
}
});
自定义事件
var button = Ext.create('Ext.Button', {
renderTo: Ext.getBody(),
text: "Just wait 2 seconds",
listeners: {
myEvent: function(button, points) {
Ext.Msg.alert('Success!', 'myEvent fired! You score ' + points + ' points');
}
}
});
Ext.defer(function() {
var number = Math.ceil(Math.random() * 100);
button.fireEvent('myEvent', button, number);
}, 2000);
监听DOM事件
var container = Ext.create('Ext.Container', {
renderTo: Ext.getBody(),
html: 'Click Me!',
listeners: {
click: function(){
Ext.Msg.alert('Success!', 'I have been clicked!')
}
}
});
container.getEl().on('click', function(){
this.fireEvent('click', container);
}, container);
如果要监听 Ext.Component
组件下的 DOM 元素事件,可以为事件监听添加 element
选项:
new Ext.panel.Panel({
width: 400,
height: 200,
dockedItems: [{
xtype: 'toolbar'
}],
listeners: {
click: {
//bind to the underlying el property on the panel
element: 'el',
fn: function(){ console.log('click el'); }
},
dblclick: {
//bind to the underlying body property on the panel
element: 'body',
fn: function(){ console.log('dblclick body'); }
}
}
});