jQuery Mobile load new data only

57 views Asked by At

I'm working on this project for learning purposes. The tasks for now are very simple:

  1. Populate data from DB using $.getJSON.
  2. Check every 'n' seconds for new data and append it to the list.
  3. Notify user about new data changes.

Here is the example of where I got so far: ( JSBin /Don't forget to run js) All the issues will be visible when running the example.

Here is the JS code that i have:

$(document).bind('pageinit', function(){

    var $myList = $( "#myList" );
    var newItems = [];

  function loadList(){  
  $.getJSON("http://jsbin.com/vayeni/2.js",function(data){

   $.each(data, function( index, value ) {

     newItems.push( "<li><a>" + value.airline + "</a></li>" );
           if(data>newItems){
            alert('New Entry');
            data=newItems;
      }
   });
        $myList.append( newItems.join( "" ) );
        $myList.listview( "refresh" );
        setTimeout(loadList,1000);
  });
  }
    loadList();
});

Thanks for your help !

1

There are 1 answers

8
Peter Kostov On BEST ANSWER

Your data comparison is not correct.

You are comapring this:

<li><a>JetBlue</a></li>
<li><a>Continental</a></li>
...

to this:

  {
    "id": "1",
    "airline": "JetBlue",
    "number": "222",
    "people": "3",
    "time": "12:20"
  },
  {
    "id": "2",
    "airline": "Continental",
    "number": "222",
    "people": "5",
    "time": "23:21"
  },

There will be always inequality.

You should use another approach. For example, if the id field from your JSON array is an unique one you can attach it to each item from the unordered list as an id attribute. For example:

newItems.push( "<li id=\"" + value.id + "\"><a>" + value.airline + "</a></li>" );

This way, at each iteration you can check if the incomming JSON item already exists into your list and add it when there is no match. Eg:

if (!$myList.find('#' + value.id).length) {
  newItems.push( "<li id=\" + value.id + \"><a>" + value.airline + "</a></li>" );
}

Finally, you can append the newItems contents directly if there are items inside:

if (newItems.length > 0) {
  $myList.append( newItems.join( "" ) );  
}

Here is the edited snippet: JSBin