2015-01-21 58 views
0

我需要你的幫助。可以說我有2個文件。commonJs中的addEventListener

文件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 

回答

3

事件偵聽器與視圖,並在test功能有關。所以,當你這樣做:

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

您試圖訪問backgroundColorviewthis.view內。

捕捉外部範圍你追加事件前,當執行點擊使用它:

function test(){ 
    var _this = this; 

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

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

這應該給你你期待的正確參考。

+0

非常感謝 – user2478240 2015-01-21 08:37:45