我想在创建的组合框中添加一个回调,所以最初我这样做了:
{
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'侦听器调用“天然”函数的情况下为回调提供索引变量?
发布于 2019-03-01 07:59:41
我将把函数的引用传递给回调参数。你现在要做的就是调用这个函数。
// 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);
});当您传递一个函数时,您不需要说它需要接收的参数。
anotherFunction将使用hello字符串调用回调(接收到的函数),因此根据函数的不同,它将做一些事情:
this.anotherFunction(function(param) {
console.log('I print a different message:', param);
});最后一条将打印:我打印另一条消息: hello
https://stackoverflow.com/questions/54939868
复制相似问题