2012-07-05 107 views
0

我正在通過鈦的最佳實踐閱讀,我想知道爲什麼這似乎並沒有工作可以告訴我什麼改變與api?鈦沒有運行功能點擊

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

UI/ToggleBox.js - 在app.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; 

使用範例

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方法從添加事件偵聽器調用時?

回答

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;