Javascript ExtJS3.4。回调
我想向已创建的组合框添加回调,因此最初我这样做:Javascript ExtJS3.4。回调,javascript,extjs,Javascript,Extjs,我想向已创建的组合框添加回调,因此最初我这样做: { fieldLabel : i18n._('Department code'), xtype : 'combo', ... store : ..., listeners : { scope : this, 'select': function(index) { self.getLi
{
fieldLabel : i18n._('Department code'),
xtype : 'combo',
...
store : ...,
listeners : {
scope : this,
'select': function(index) {
self.getListOfPossibleDrives(index);
}
}
}
{
fieldLabel : i18n._('Department code'),
xtype : 'combo',
...
store : ...,
listeners : {
scope : this,
'select': self.getListOfPossibleDrives(chosenBook)
}
}
虽然它工作,但我不认为这是一个干净的解决方案,因为我只想留下一个回调。 所以我这样做了:
{
fieldLabel : i18n._('Department code'),
xtype : 'combo',
...
store : ...,
listeners : {
scope : this,
'select': function(index) {
self.getListOfPossibleDrives(index);
}
}
}
{
fieldLabel : i18n._('Department code'),
xtype : 'combo',
...
store : ...,
listeners : {
scope : this,
'select': self.getListOfPossibleDrives(chosenBook)
}
}
但很自然,我现在有了未解析的变量
chosenBook
。是否可以在不从'select'
侦听器调用“natural”函数的情况下为回调函数指定索引变量?我会将函数的w引用传递给回调参数。现在要做的是调用函数
// Definition of the callback function
this.getListOfPossibleDrives = function (chosenBook) {
// Your code when a book is selected
}
// Configuration for the comboBox
var config = {
fieldLabel : i18n._('Department code'),
xtype : 'combo',
...
store : ...,
listeners : {
scope : this,
'select': self.getListOfPossibleDrives
}
}
在参数或对象中执行somefunction()时(使用括号/方括号),实际上是在调用函数,因此配置中需要的是,或者像开始时那样定义函数,或者传递对另一个函数的引用
// Definition of the callback function
this.getListOfPossibleDrives = function (chosenBook) {
// Your code when a book is selected
}
// Configuration for the comboBox
var config = {
fieldLabel : i18n._('Department code'),
xtype : 'combo',
...
store : ...,
listeners : {
scope : this,
'select': self.getListOfPossibleDrives
}
}
这不是魔法,只是你可以把函数作为参数传递。例如,您可以拥有以下功能:
this.myFunctionOne = function (myStringParam) {
// Do things
}
this.anotherFunction = function (callback) {
// Do things... and call a callback function received as param
callback('hello');
}
this.anotherFunction(this.myFunctionOne);
// Or you can do directly
this.anotherFunction(function(param) {
console.log(param);
});
// With ES6 syntax
this.anotherFunction((param) => {
console.log(param);
});
传递函数时,不需要说出它需要接收的参数
另一个函数将使用hello字符串调用回调(接收的函数),因此根据函数的不同,它将执行以下操作:
this.anotherFunction(function(param) {
console.log('I print a different message:', param);
});
最后一个将打印:我打印另一条消息:hello为什么不将引用放在函数中?选择:self.getListofPossibleDrive而不调用它!;-)我不是一个真正的JS人,PHP是我的堆栈,所以我不知道为什么和如何工作:)你能给我一些东西给谷歌吗?这叫什么?这是一个JS的魔术与回调还是?