0

In my Titanium app, I have a form with 6 identical fields, the only difference being their title. Instead of repeating code (bad practice, more work, etc.) I used a for-loop to dynamically create each field with 2 labels and a view:

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

I tried adding this to the bottom:

view.addEventListener('focus',function(e){
    Ti.API.info("Clicked on " + label.text);
});

but to no avail. Is there a way to dynamically create event listeners or am I required to have a separate view object for each field so that it can be tied directly to an event listener?

eliot
  • 1,319
  • 1
  • 14
  • 33

2 Answers2

1

Focus and blur events don't bubble, so in this case you'll need to listen to each individual field.

You can sort of hack around it using mouse events, but it's not a great solution: http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html

Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
1

Ti.UI.View doesn't have a focus event. If you wanted to listed to another event, like click, you can you can add the event listener to each view in the for loop like this:

(function(v, msg){
    v.addEventListener('click',function(e){
        Ti.API.info("Clicked on " + msg);
    });
})(view, label.txt);

If you are going to add text fields, which do have focus events, you can add the listener the same way.

Adam Paxton
  • 1,422
  • 1
  • 12
  • 11
  • I'm not planning on adding text fields but this looks awesome. I can't say I understand what is going on here though. Would you mind explaining what the (view, label.text) is after the function, or how this works? – eliot Mar 13 '13 at 20:50
  • 1
    This is an anonymous, self invoking (or self calling) function. We are passing view and label.text to it, which are called v and msg as the function's arguments. The `view` variable was getting changed with every iteration of the for loop, and by doing this, we are locking in the view as `v`, which won't get overwritten. There are some better explanations [here](http://stackoverflow.com/questions/6783723/what-is-this-function) and [here](http://blog.mgechev.com/2012/08/29/self-invoking-functions-in-javascript/). – Adam Paxton Mar 13 '13 at 21:56