4
我已经用OOP JavaScript和事件处理程序作用域将这种奇怪的行为加以计算。这是我的代码:在Titanium下开发钛JavaScript事件处理程序和类范围
MyClass = function()
{
this.var1 = '50';
this.button = Ti.UI.createButton({
...
});
this.button.parentRef = this;
this.button.addEventListener('click', function(e){
var self = e.source.parentRef;
console.log(self.var1);
console.log(self.var2);
});
this.var2 = 'Test';
...
/* this.button is then added to a view */
};
...
var c = new MyClass();
...
当我按一下按钮,在我的控制台我希望找到:
50
Test
但实际上结果是:
50
<null>
如果我移动任务
的this.var2 ='测试'
this.button.addEventListener
语句之前
,结果是:
50
Test
听上去好像this.button.parentRef =这个任务是通过复制而不是通过参考...
这种行为的原因是什么?
你确定'e.source'是按钮本身吗?这甚至不是一个标准的事件属性。 – Bergi
“Ti.UI.createButton”是否返回实际的DOM元素(事件被触发)本身还是创建一个包装? – Bergi
@Bergi它创建一个[代理对象](http://developer.appcelerator.com/blog/2012/02/what-is-a-titanium-proxy-object.html)到原生的android/ios按钮 – C5H8NNaO4