来自 C++ 背景,我在 Javascript/ExtJS 函数范围界定方面有点迷茫——特别是在处理事件时。
假设我有一个 Controller ,它监听许多不同的事件。这些事件可能来自托管 View 、商店、应用程序级别等。目前,我正在做这样的事情来确保正确的范围:
init: function() {
me.control({
'someSelector': {
someEvent: me.onSomeEvent.bind(me)
},
...
});
me.application.on({
applicationEvent: me.onApplicationEvent.bind(me)
});
},
onSomeEvent: function() {...},
onApplicationEvent: function() {...},
这是处理事情的正确方法吗?我害怕在 onSomeEvent()
和 onApplicationEvent
中使用 this
除非我特别知道 this
指向什么.想法?
edit:这里有一些示例代码来说明 this
可能会产生误导的地方。
init: function() {
this.control({
'uploadform *': {
formUpload: this.onFormUpload
}
});
},
onFormUpload: function(form) {
if(form.isValid()) {
var formData = form.getValues();
Ext.Ajax.request({
url: 'upload',
method: 'POST',
jsonData: {
form: formData
},
success: this.onFormUploadSuccess // here, this is the controller
});
}
},
onFormUploadSuccess: function() {
... // here, this isn't the controller
this.application.fireEvent('dealAdded'); // this.application === undefined!!
}
最佳答案
尽管 JS 中的作用域可能会造成混淆,但不要害怕它。 你的 Controller 维护范围,所以你不需要丑化你的代码。它应该看起来像这样:
Ext.define('Pandora.controller.Station', {
extend: 'Ext.app.Controller',
...
init: function() {
this.control({
'stationslist': {
selectionchange: this.onStationSelect
},
...
});
},
...
onStationSelect: function(selModel, selection) {
this.application.fireEvent('stationstart', selection[0]);
},
...
});
这里有一篇出色的事件处理帖子:Explain ExtJS 4 event handling .
此外,当某些东西看起来不正确时,我求助于 console.log(this)
只是为了确保我正在查看正确的范围。
编辑
在看到您提供的示例后,问题不在于 Controller 本身,而在于 Ajax 请求是异步的并且默认情况下在 Window 范围内执行。 ExtJS 允许您在请求中使用 scope:this
配置设置范围,这会将 Controller 设置为成功回调的范围。
Ext.Ajax.request({
url: 'upload',
method: 'POST',
jsonData: {
form: formData
},
success: this.onFormUploadSuccess // here, this is the controller
,scope:this
});
关于javascript - ExtJS:范围混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18793008/