javascript ExtJs 4 回调

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12253249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:42:51  来源:igfitidea点击:

ExtJs 4 callbacks

javascriptextjsextjs4extjs4.1extjs4.2

提问by leonardorame

I had a hard time trying to find out why my assignments where lost, and found that callbacks scope was different than I thought.

我很难找出我的作业丢失的原因,并发现回调范围与我想象的不同。

What I did was to create a variable in a controller, then trying to pass a callback to a window created by the controller, then, on an event on that window, call-back a function in the controller.

我所做的是在控制器中创建一个变量,然后尝试将回调传递给控制器​​创建的窗口,然后在该窗口上的事件上回调控制器中的函数。

For example, in my controller I have:

例如,在我的控制器中,我有:

callWindow: function(){
  var myWin = Ext.Create('MyApp.view.myWin', {doSomething: this.doSomething});
},

doSomething: function(data){
  this.myData = data;
},

useTheData: function(){
  console.log(this.myData);
}

In myWin's controller, I have an even handler that calls doSomething this way:

在 myWin 的控制器中,我有一个偶数处理程序,它以这种方式调用 doSomething:

onBtnClick: function(button){
  var win = button.up('window');
  var data = {id: 1, name: "John"}; // please, don't pay attention to this, it's a record I'm passing to the caller.
  win.doSomething(data);
}

As you can see, in "doSomething" function, I'm assigning the controller var myData, with the value passed by the window's controller. Initially I thought the scope of "doSomething" was the caller controller, but it's the window's controller, that's why useTheData gives an error saying this.myData is null.

如您所见,在“doSomething”函数中,我使用窗口控制器传递的值分配控制器 var myData。最初我认为“doSomething”的范围是调用者控制器,但它是窗口的控制器,这就是为什么 useTheData 给出一个错误,说 this.myData 为空。

I've solved the problem by passing a new parameter named "caller: this", and in doSomething, receiving that parameter, and using it instead of "this".

我通过传递一个名为“caller: this”的新参数解决了这个问题,在 doSomething 中,接收该参数,并使用它而不是“this”。

The question is, is there a easy (with less steps) way to do this?.

问题是,是否有一种简单(步骤更少)的方法来做到这一点?

回答by sra

You need to apply a scope for your callback to the window and use Ext.callback

您需要将回调范围应用于窗口并使用Ext.callback

callWindow: function(){
  var myWin = Ext.Create('MyApp.view.myWin', {doSomething: this.doSomething, scope: this});
},

onBtnClick: function(button){
  var win = button.up('window');
  var data = {id: 1, name: "John"}; // please, don't pay attention to this, it's a record I'm passing to the caller.
  Ext.callback(win.doSomething, win.scope, [data]);
}

This is one way, your solution is another and there are even more.

这是一种方式,您的解决方案是另一种方式,还有更多。