[英]addEventListener in commonjs
I need your help on this. 我需要你的帮助。 Lets say I have 2 files. 可以说我有2个文件。
file1 文件1
function test(){
this.view= Ti.UI.createView({
backgroundColor : 'white'
});
}
module.exports = test;
and in file 2 并在文件2中
var view = Ti.UI.createView();
var a = require('file1');
a = new test();
view.add(a.view);
//no problem
And now I want to add eventListeners to the view. 现在,我想将eventListeners添加到视图中。
file2 文件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
But is there a way to add eventlisteners to view in file 1? 但是,有没有一种方法可以添加事件侦听器以在文件1中查看? something like this 像这样的东西
file1 文件1
function test(){
this.view = Ti.UI.createView({
backgroundColor : 'white'
});
this.view.addEventListener('click',function(){
this.view.backgroundColor = 'red';
});
}
Doing this will give me the following error 这样做会给我以下错误
Uncaught TypeError: Cannot set property 'backgroundColor' of undefined
The event listener is related with the view and with the test
function. 事件侦听器与视图和test
功能相关。 So when you do: 因此,当您这样做时:
this.view.addEventListener('click',function(){
this.view.backgroundColor = 'red';
});
You are trying to access the backgroundColor
inside the view
inside the this.view
. 您试图访问backgroundColor
内部view
里面this.view
。
Capture the outside scope before you append the event and use it when execute the click: 在追加事件之前捕获外部作用域,并在执行单击时使用它:
function test(){
var _this = this;
this.view = Ti.UI.createView({
backgroundColor : 'white'
});
this.view.addEventListener('click',function(){
_this.view.backgroundColor = 'red';
});
}
This should give you the correct reference you are expecting. 这应该为您提供正确的参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.