在我的Titanium應用程序中,我有一個包含6個相同字段的表單,唯一的區別是它們的標題。而不是重複碼(不好的做法,更多的工作,等)的我用一個for循環動態創建與2個標籤的每個字段和一個視圖:動態分配事件Listseners
//Required info
var startht = 30;
var sz = 40;
var width = '90%';
var labelgrp1 = new Array('Field 1', 'Field 2', 'Field 3', 'Field 4', 'Field 5', 'Field 6');
var viewbg = '#D4D4D4';
//For the first group of labels
for(var i=0; i<labelgrp1.length; i++) {
var view = Titanium.UI.createView({
borderColor:'#000',
backgroundColor:viewbg,
touchEnabled: true,
width:width, height:40,
top: startht + i * (sz - 1)
});
var label = Ti.UI.createLabel({
color: '#303030',
font: { fontSize:16 },
shadowColor: '#aaa',
shadowOffset: {x:1, y:1},
text: labelgrp1[i],
left:10,
width: 'auto', height: 'auto'
});
var symbol = Ti.UI.createLabel({
color: '#303030',
font: { fontSize:14 },
right:10,
text: '>',
width: 'auto', height: 'auto'
});
view.add(label);
view.add(symbol);
win.add(view);
}
我嘗試添加這對底部:
view.addEventListener('focus',function(e){
Ti.API.info("Clicked on " + label.text);
});
但無濟於事。有沒有辦法動態創建事件偵聽器,還是我需要爲每個字段設置一個單獨的視圖對象,以便它可以直接綁定到事件偵聽器?
我不打算添加文本字段,但看起來很棒。我不能說我理解這裏發生了什麼。你介意解釋一下(view,label.text)在函數後面,或者它是如何工作的? – eliot 2013-03-13 20:50:46
這是一個匿名的自我調用(或自我調用)函數。我們將view和label.text傳遞給它,它被稱爲v和msg作爲函數的參數。 'view'變量隨着for循環的每次迭代而變化,通過這樣做,我們將視圖鎖定爲'v',這將不會被覆蓋。有一些更好的解釋[這裏](http://stackoverflow.com/questions/6783723/what-is-this-function)和[這裏](http://blog.mgechev.com/2012/08/29/自我呼叫函數式的JavaScript /)。 – 2013-03-13 21:56:08
完美的解釋。簡潔明白,謝謝! – eliot 2013-03-13 23:09:09