0

我正在阅读钛最佳实践,我想知道为什么这似乎不起作用,有人可以告诉我 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);

从添加事件侦听器调用时,它似乎不想返回 setActive 方法?

4

1 回答 1

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;
于 2012-07-05T14:48:13.517 回答