How to show details from ArrowDB for individual objects #appcelerator

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-17 05:08:06

问题


I have queried from ArrowDB and gotten a list of events, now I want each individual event details when the specific view is clicked. My code as shown below works except that it puts the details from all the queried events on the opened window, and it shows the last queried event at the top.

How can I do this please? My brain just can't fix this.

 Cloud.Events.query(function (e) {
        if (e.success) {
            alert('Success:\n' + 'Count: ' + e.events.length);

            for (var i = 0; i < e.events.length; i++) {
                var event = e.events[i];
                alert('id: ' + event.id + '\n' +
                      'name: ' + event.name + '\n' +
                      'start time: ' + event.start_time);
                var holdview = Ti.UI.createView({
                     backgroundColor: '#d3d3d3',
                     backgroundImage: 'testview.png',
                     width: '85%',
                     height: '85%',
                     top: '5%'
                });

                //adding holdview to a scrollable view

               xperiencesscrollableview.addView(holdview);

               var testlabeltitle = Ti.UI.createLabel({
                    top: '5%',
                    width: '65%',
                    height: '10%',
                    left: '20%',
                    text: event.name
               }); 
               //it works well to this point and shows each event separately on views
               holdview.add(testlabeltitle);
       //adding forEach as suggested as an answer            
               e.events.forEach(function(event) {
        holdview.addEventListener('click',function(e){

            var detailstestname = Ti.UI.createLabel({
        top: '5%',
        width: '65%',
        height: '10%',
        left: '20%',
        text: event.name,
        color: 'black',
        backgroundColor: 'white'
        }); 
       //Page for event details
        eventdetailspage.open();
        eventdetailspage.add(detailstestname);
        });
 });    
               //at this point it messes up
            }
         }
     });

回答1:


The problem lies in that you are using a for-loop whose code block does not have its own scope. The event.name you use for the detailstestname label will always be the event of the last loop by the time the loop has finished and the click event is handled.

You could either use a closure:

for (var i = 0; i < e.events.length; i++) {
  (function(event) {
    ..
  })(e.events[i]);
}

Or use .forEach():

e.events.forEach(function(event) {
  ..
});


来源:https://stackoverflow.com/questions/35020543/how-to-show-details-from-arrowdb-for-individual-objects-appcelerator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!