Titanium 单击时未运行功能

Titanium 单击时未运行功能,titanium,Titanium,我正在阅读Tianium的最佳实践,我想知道为什么这似乎不起作用。有人能告诉我api有什么变化吗 ui/ToggleBox.js-自定义复选框 function ToggleBox(onChange) { this.view = Ti.UI.createView({backgroundColor:'red',height:50,width:50}); //private instance variable var active = false;

我正在阅读Tianium的最佳实践,我想知道为什么这似乎不起作用。有人能告诉我api有什么变化吗

ui/ToggleBox.js-自定义复选框

   function ToggleBox(onChange) {
      this.view = Ti.UI.createView({backgroundColor:'red',height:50,width:50});

      //private instance variable
      var active = false;

      //public instance functions to update internal state, execute events
      this.setActive = function(_active) {
        active = _active;
        this.view.backgroundColor = (active) ? 'green' : 'red';
        onChange.call(instance);
      };

      this.isActive = function() {
        return active;
      };

      //set up behavior for component
      this.view.addEventListener('click', function() {
        this.setActive(!active);
      });
    }
    exports.ToggleBox = ToggleBox;
app.js中的示例用法

var win = Ti.UI.createWindow({backgroundColor:'white'});
var ToggleBox = require('ui/ToggleBox').ToggleBox;

var tb = new ToggleBox(function() {
  alert('The check box is currently: '+this.isActive());
});
tb.view.top = 50;
tb.view.left = 100;

win.add(tb.view);
从添加事件侦听器调用时,它似乎不想返回setActive方法?

单击侦听器中的“this”不是您所期望的。(可能是视图)因为您的函数已经是ToggleBox上下文,所以最简单的解决方案就是直接引用setActive。“this.”仅对您为其他代码公开的API是必需的

function ToggleBox(onChange) {
  var view = this.view = Ti.UI.createView({backgroundColor:'red',height:50,width:50});

  //private instance variable
  var active = false;

  //public instance functions to update internal state, execute events
  var setActive = this.setActive = function(_active) {
    active = _active;
    view.backgroundColor = (active) ? 'green' : 'red';
    onChange.call(instance);
  };

  var isActive = this.isActive = function() {
    return active;
  };

  //set up behavior for component
  view.addEventListener('click', function() {
    setActive(!active);
  });
}
exports.ToggleBox = ToggleBox;