简体   繁体   English

Titanium JavaScript事件处理程序和类范围

[英]Titanium JavaScript event handler and class scope

developing under Titanium I have encountred this strange behaviour with OOP JavaScript and event handler scope. 在Titanium下开发我用OOP JavaScript和事件处理程序范围来掩盖这种奇怪的行为。 This is my code: 这是我的代码:

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

When I click on the button, in my console I would expect to find: 当我点击按钮时,在我的控制台中我希望找到:

50
Test

But actually the result is: 但实际上结果是:

50
<null>

If I move the assignment 如果我移动作业

this.var2 = 'Test' this.var2 ='测试'

before the 之前

this.button.addEventListener this.button.addEventListener

statement, the result is: 声明,结果是:

50
Test

Sounds like that the this.button.parentRef = this assignment is by copy and not by reference... 听起来像this.button.parentRef =这个赋值是复制而不是引用...

What is the cause of this behavior ? 这种行为的原因是什么?

You are correct. 你是对的。

What you are doing has wrinkles with Titanium, whenever you add an attribute to a Titanium native object, it is passed by value, as the underlying object (your view) is actually a native mapped to a JavaScript object. 您正在做的事情与Titanium有关,每当您向Titanium本机对象添加属性时,它都会按值传递,因为底层对象(您的视图)实际上是本机映射到JavaScript对象。 So what happens is that the current value of that object (in your case this ) is sent across the Javascript-to-native bridge and set as a property of the native object (or something like that). 所以会发生的是,该对象的当前值(在您的情况下this )通过Javascript到本机桥发送并设置为本机对象的属性(或类似的东西)。

What it comes down to is that, any attributes on a native object you set are pretty much cloned by the object, thats why you are seeing the above functionality. 它归结为,您设置的本机对象上的任何属性都被对象克隆得很多,这就是您看到上述功能的原因。

So what are some ways to deal with this? 那么有什么方法可以解决这个问题呢?

This is the easy way: 这是简单的方法:

var self = this;
this.button.addEventListener('click', function(e){
    console.log(self.var1);
    console.log(self.var2);
});

It somewhat pollutes your button listener scope, but at least its not in global scope. 它有点污染你的按钮监听器范围,但至少它不在全局范围内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM