2011-11-24 17 views
1

这可能是JavaScript范围缺乏理解,但为什么我不能在按下按钮时从面板项目元素中访问this.onLoginTap()。我收到一个错误,指出this.onLoginTap不存在。我现在的解决方案是将项目的声明移动到initComponent方法中,但我仍然想知道为什么我不能访问这个方法。为什么我不能在处理程序中访问Sencha Touch JavaScript配置对象中的方法?

感谢,

菲利普

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); 

回答

3

的 “this” 指针确实没有执行的时刻指向按钮。

但最重要的,这里有一些解决方案:

解决方案1:

检查处理程序的文档: http://docs.sencha.com/touch/1-1/#!/api/Ext.Button-cfg-handler

你会看到,你可以从实际的按钮实例处理函数:

handler: function(button, event) { 
    var parent = button.ownerCt; // get your main panel, the owner of the button 
    parent.onLoginTap(); 
} 

我没有测试过代码,但基本的想法应该是b e清楚。

解决方案2:

  • 从配置
  • 取出处理程序分配在initComponent处理程序:

    // Get the button and add a listener to it: 
    this.items.get(0).addListener('tap', this.onLoginTap); 
    

解决方案3:

同溶液2除了您分配处理程序/监听rs来自控制器内部。 控制器管理面板/视图,因此它将所有逻辑绑定在一起是有道理的。

+0

感谢您的答复。解决方案1不起作用,所以我仍然难以确定范围问题。我试过了,button.ownerCt不包含该方法。解决方案2和3是合理的,但是,个人而言,我更喜欢在定义了ui组件的地方附加处理程序调用,以便我可以看到发生了什么。但是,我愿意对此进行说服;-)需要进一步思考这个......再次感谢。 –

1

你有没有尝试过这样的:

items: [ { 
      xtype: 'button', 
      text: 'Log In', 
      ui: 'confirm', 

      handler: function() { 
       this.up('panel').onLoginTap(); // this.onLoginTap is undefined here at runtime. 
      } 
     }] 

编辑:刚才遇到同样的情况 - 我的是一个MVC的设置和我的按钮是位于FormPanel。我能够使用this.up('formpanel')访问主视图,所以上述可能适用于你(我也没有设置范围在按钮中,因为它不适用于它)

+0

不,'this'是指DOMWindow,而不是实际的视图类。感谢您的反馈。 –

+0

@PhilipMurphy比你还有别的错误。处理程序配置调用按钮的轻击事件。 Sencha文档清楚地表明,tap事件中的'this'是指按钮本身。雅秀的代码应该可以工作。但是,您可以尝试使用“this.parent.onLoginTap()”来查看是否更好。 – PhillipKregg

相关问题