Function 为什么可以';我是否可以从处理程序访问Sencha Touch JavaScript配置对象中的方法?
这可能是缺乏对JavaScript作用域的理解,但为什么我不能在按下按钮时从Panel items元素中访问这个.onLoginTap()。我收到一个错误,指出this.onLoginTap不存在。目前我的解决方案是将项的声明移动到initComponent方法中,但我仍然想知道为什么我不能访问这个方法 谢谢 菲利浦Function 为什么可以';我是否可以从处理程序访问Sencha Touch JavaScript配置对象中的方法?,function,scope,sencha-touch,handler,Function,Scope,Sencha Touch,Handler,这可能是缺乏对JavaScript作用域的理解,但为什么我不能在按下按钮时从Panel items元素中访问这个.onLoginTap()。我收到一个错误,指出this.onLoginTap不存在。目前我的解决方案是将项的声明移动到initComponent方法中,但我仍然想知道为什么我不能访问这个方法 谢谢 菲利浦 app.myView = Ext.extend(Ext.Panel, { fullscreen: true, scroll: 'vertical',
app.myView = Ext.extend(Ext.Panel, {
fullscreen: true,
scroll: 'vertical',
layout: {
type: 'vbox'
},
items: [{
layout: {
type: 'hbox'
},
items: [ {
xtype: 'button',
text: 'Log In',
ui: 'confirm',
handler: function() {
this.onLoginTap(); // this.onLoginTap is undefined here at runtime.
}
}]
}],
// Controller Dispatchers
onLoginTap: function() {
console.log('onLoginTap');
},
initComponent: function() {
app.myView.superclass.initComponent.apply(this, arguments);
}
});
Ext.reg('myView', app.myView);
“this”指针在执行时确实没有指向按钮
但最重要的是,以下是一些解决方案:
解决方案1:
检查处理程序的文档:
您将看到,您可以从处理程序函数中获得实际的按钮实例:
handler: function(button, event) {
var parent = button.ownerCt; // get your main panel, the owner of the button
parent.onLoginTap();
}
我还没有测试代码,但是基本思想应该很清楚
解决方案2:
- 从配置文件中删除处理程序
- 在initComponent中分配处理程序:
// Get the button and add a listener to it: this.items.get(0).addListener('tap', this.onLoginTap);
handler: function(button, event) {
var parent = button.ownerCt; // get your main panel, the owner of the button
parent.onLoginTap();
}
我还没有测试代码,但是基本思想应该很清楚
解决方案2:
- 从配置文件中删除处理程序
- 在initComponent中分配处理程序:
// Get the button and add a listener to it: this.items.get(0).addListener('tap', this.onLoginTap);
items: [ {
xtype: 'button',
text: 'Log In',
ui: 'confirm',
handler: function() {
this.up('panel').onLoginTap(); // this.onLoginTap is undefined here at runtime.
}
}]
编辑:刚刚遇到同样的情况-我的是MVC设置,我的按钮在一个formpanel中。我可以使用此.up('formpanel')访问主视图,因此上述内容可能对您有效(我也没有在按钮中设置范围,因为它不起作用)您是否尝试过此方法:
items: [ {
xtype: 'button',
text: 'Log In',
ui: 'confirm',
handler: function() {
this.up('panel').onLoginTap(); // this.onLoginTap is undefined here at runtime.
}
}]
编辑:刚刚遇到同样的情况-我的是MVC设置,我的按钮在一个formpanel中。我可以使用此.up('formpanel')访问主视图,因此上面的内容可能对您有用(我也没有在按钮中设置范围,因为它不起作用)感谢您的回复。解决方案1不起作用,所以我仍然被范围界定问题难住了。我已经尝试过了,button.ownerCt不包含该方法。解决方案2和3是合理的,但是,就我个人而言,我更喜欢在定义ui组件的地方附加处理程序调用,这样我就可以看到将要发生什么。然而,在这一点上,我愿意接受说服;-)需要再考虑一下这个。。。再次感谢。谢谢你的回复。解决方案1不起作用,所以我仍然被范围界定问题难住了。我已经尝试过了,button.ownerCt不包含该方法。解决方案2和3是合理的,但是,就我个人而言,我更喜欢在定义ui组件的地方附加处理程序调用,这样我就可以看到将要发生什么。然而,在这一点上,我愿意接受说服;-)需要再考虑一下这个。。。再次感谢。不,“this”指的是DOMWindow,而不是实际的视图类。谢谢你的反馈。@PhilipMurphy,你还有其他问题。处理程序配置调用按钮的点击事件。Sencha文档清楚地表明,点击事件中的“this”指的是按钮本身。Yashua的代码应该有效。但是,您可以尝试使用“this.parent.onLoginTap()”,看看效果是否更好。不,“this”指的是DOMWindow,而不是实际的视图类。谢谢你的反馈。@PhilipMurphy,你还有其他问题。处理程序配置调用按钮的点击事件。Sencha文档清楚地表明,点击事件中的“this”指的是按钮本身。Yashua的代码应该有效。不过,您可以尝试使用“this.parent.onLoginTap()”来代替,看看效果是否更好。