addEventListener in commonjs

addEventListener in commonjs

本文关键字:commonjs in addEventListener      更新时间:2023-09-26

我需要你的帮助。假设我有 2 个文件。

文件1

function test(){
   this.view= Ti.UI.createView({
            backgroundColor : 'white'
    });
}
module.exports = test;

并在文件 2 中

 var view = Ti.UI.createView();
 var a = require('file1');
 a = new test();
 view.add(a.view);
 //no problem

现在我想将事件侦听器添加到视图中。

文件2

 var view = Ti.UI.createView();
 var a = require('file1');
 a=new test();
 view.add(a.view);
 a.view.addEventListener('click',function(){
      a.view.backgroundColor = 'red';
 });
//no problem with this too

但是有没有办法添加事件侦听器以在文件 1 中查看? 像这样的东西

文件1

 function test(){
     this.view = Ti.UI.createView({
           backgroundColor : 'white'
     });
     this.view.addEventListener('click',function(){
              this.view.backgroundColor = 'red';
     });
 }

这样做会给我以下错误

 Uncaught TypeError: Cannot set property 'backgroundColor' of undefined

事件侦听器与视图和test函数相关。因此,当您这样做时:

this.view.addEventListener('click',function(){
          this.view.backgroundColor = 'red';
 });

您正在尝试访问this.viewview内的backgroundColor

在追加事件之前捕获外部范围,并在执行单击时使用它:

function test(){
     var _this = this;
     this.view = Ti.UI.createView({
         backgroundColor : 'white'
     });
     this.view.addEventListener('click',function(){
         _this.view.backgroundColor = 'red';
     });
 }

这应该为您提供所需的正确参考。