Ext js:全局这个变量如何使用绑定在按钮处理程序中访问?

Ext js : global this variable how to access in the button handler using bind?

我有一个全局变量 this.myItems 。 在 ext js 中,我创建了一个按钮,但在其处理程序中我无法访问 this.myItems。在处理程序中,这是指按钮,我如何绑定到 gobal 对象?有什么办法吗?

你说你有一个全局变量this.myItems。 JavaScript 中的 this 永远不是全局变量。 this指代码执行范围内对象的当前实例。

现在解决你的问题。实现这一目标的方法不止一种。

  • 您可以使用 listeners 而不是使用带有函数的 handler,它允许您将范围作为参数传递。

    listeners: {
        click: {
            fn: function(button){}, 
            scope: //put here the variable you want to access with this 
        } 
    } 
    
  • 使用 addListener,它还允许您指定一个范围。

  • 将处理函数定义为控制器的一个方法。不是在视图中设置处理程序,而是在控制器的 init 方法中设置。

    init: function() { 
        this.control({ 
            'button': { click: this.onButtonClick} 
        }); 
    },
    onButtonClick: function(button) {
    

我更喜欢第三种解决方案,因为它可以将视图和行为完全分开。 MVC 也是获得可维护代码的良好基础。