Titanium appcelerator:使用JSON加载数据时表视图中的延迟加载概念

时间:2013-10-25 11:30:06

标签: json titanium titanium-mobile appcelerator appcelerator-mobile

我使用Google Places API来显示各种地方。我希望一次显示20个位置,当用户滚动表视图并到达最后一个字段时,我想添加其余数据,依此类推。我创建了一个函数,它返回视图并完美地排除了一件事。当没有其他数据可用时,它会继续加载已加载的最后一个数据。这是我的代码。

Ti.include('Functions/get_lat_long.js');
var myTable = Ti.UI.createTableView();
var next_page;
var nxt_pge_tkn;
var tableData = [];
function json_parsing(url,firsttime,winloading)
{

var view1=Ti.UI.createView({
        //height : '100%',
        width : '100%',
        backgroundColor : '#EDDA74',
        top : '10%',
        borderColor : "black"
    });
//For storing url in case next_page_token variable is invalid

var curloc=Ti.App.Properties.getString("curlocation");
//calling method in order to retrive latitude and longitude of current location
get_latitude_longitude(curloc);
//setting the base url that have been initialized in global.js file
var baseurl=Ti.App.Properties.getString("preurl");
//storing lat and lng file that have been initialized in get_lat_lon.js file get_latitude_longitude function 
var lat=Ti.App.Properties.getString("curlat");
var lng=Ti.App.Properties.getString("curlng");
//Storing radius which have been initialized in global.js file
var radiusmts=Ti.App.Properties.getInt("curradius")*1000;
//setting location type from the value that have been selected in app.js file by user
var loc_type=Ti.App.Properties.getString("curcategory");
//fetching and storing key which have been initialized in global.js file
var key=Ti.App.Properties.getString("apikey");
if(firsttime==true)
{
    winloading.open();
    var completeurl=baseurl+lat+","+lng+"&radius=" + radiusmts+ "&types=" + loc_type+ "&sensor=false&key=" + key;
}
else
{
    winloading.show();
    var completeurl=url;
}


var client = Ti.Network.createHTTPClient();


Ti.API.info("complete url " +completeurl);
client.open('GET',completeurl);
client.onload = function(e) {
       //For getting next_page_token so that next page results could be displayed
      var json = JSON.parse(this.responseText);

      if(json.next_page_token)
      {
        Ti.API.info("Next page token found ");
        next_page=true;
        nxt_pge_tkn=json.next_page_token;
      }
      else
      {     
        Ti.API.info("Next page token not found ");
        next_page=false;
      }

      if(json.results.length==0)
      {
        var lblno_record=Titanium.UI.createLabel({
            text : "No Record Found",
            color : "black",
            font : {fontSize : "25%" }
        });
      view1.add(lblno_record);
      }
      else
      {
      for(var i=0; i <json.results.length;i++) 
            {
            //Ti.API.info("Place " + json.results[i].name+ " Lat " + json.results[i].geometry.location.lat + " Lng " + json.results[i].geometry.location.lng);
            var row = Ti.UI.createTableViewRow({
                className : "row"
                //height : "80%"
                });
            //For temporary storing name in name variable
            var name=json.results[i].name;
            //Logic for shortening string in order to avoid overlapping of string
            (name.length>35)?name=name.substr(0,34)+ "..." :name=name;
            //Create label for displaying the name of place
            var lblname=Ti.UI.createLabel({
                //text : json.results[i].name,
                text :  name,
                color : "black",
                font : {fontSize : "20%"},
                left : "22%",
                top : "5%"
                });
             Ti.API.info("Name :- " + name);
            row.add(lblname);

            var add= json.results[i].vicinity;
            (add.length>125) ? add=add.substr(0,123)+ ". ." : add=add;

            var lbladdress=Ti.UI.createLabel({
                text : add,
                color : "black",
                font : {fontSize : "15%"},
                left : "22%",
                top : "30%",
                width : "71%"
                });
            row.add(lbladdress);

            var imgico=Ti.UI.createImageView({
                image : json.results[i].icon,
                height : "90",
                width : "90",
                left : "1%",
                top : "3%"
                //bottom : "10%"
                });
            row.add(imgico);      
            tableData.push(row);
            }
            //setting data that have been set to mytable view
            myTable.setData(tableData);
            view1.add(myTable);

            }
    winloading.hide();
};
client.onerror=function(e){
    alert("Network Not Avaliable");
};

myTable.addEventListener('scroll',function(e){
            var first=e.firstVisibleItem;
            var visible=e.visibleItemCount;
            var total=e.totalItemCount;
            Ti.API.info("Value of next_page_token before loop " + next_page);
            if(next_page==true &&  first+visible==total )
            {
                Ti.API.info("Value of next_page_token in loop " + next_page);
                var newurl="https://maps.googleapis.com/maps/api/place/nearbysearch/json?pagetoken="+nxt_pge_tkn+"&sensor=false&key="+key;
                firsttime=false;
                winloading.show();
                //myTable.removeEventListener('scroll',function(e){});
                json_parsing(newurl,firsttime,winloading);
                //get_next_page(newurl);
            }
        });



client.send();
return view1;
client.clearCookies();
}

1 个答案:

答案 0 :(得分:0)

我正在查看您的代码,我想指出:

  • 该块有一个重要问题:

    myTable.addEventListener('scroll',function(e){
    
    ...
    
    });
    

    每次调用json_parsing函数时都会调用此块。因此,您将有几个附加到myTable滚动事件的函数。我确定这不是你的意图。你应该把它从json_parsing中删除。

  • 关于您的具体问题,您可以尝试查看client.onload函数中的json.next_page_token值:

    client.onload = function(e) {
    //For getting next_page_token so that next page results could be displayed
    var json = JSON.parse(this.responseText);
    Ti.API.info(JSON.stringify(this.responseText);
    if(json.next_page_token)
    {
    ...
    

    可能值是空对象{}或'false'字符串,它将返回一个thruthy值。不要忘记在javascript中只有6个假值:false,undefined,null,0,''和NaN。

  • 实际上这是一个小问题,但在文档HTTPClient.onload中,必须在调用HTTPClient.open函数之前设置HTTPClient.onerror函数

  • 顺便说一下,你的json_parsing函数末尾有无法访问的代码,但我想你已经知道: - )

    client.send();
    return view1;
    client.clearCookies(); //Unreachable code