点击时钛没有运行功能

时间:2012-07-05 12:57:39

标签: titanium

我正在阅读钛最佳实践,我想知道为什么这似乎不起作用可以有人告诉我什么改变了api?

https://wiki.appcelerator.org/display/guides/Mobile+Best+Practices

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

从add事件监听器调用时,它似乎不想返回setActive方法吗?

1 个答案:

答案 0 :(得分:0)

点击监听器中的“this”并不是您所期望的。 (这可能是视图。)因为您的函数已经是ToggleBox上下文,最简单的解决方案是使用对setActive的直接引用。 “这个。”只有您为其他代码公开的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;