Rob
Rob

Reputation: 389

how to refresh jquery mobile listviews

I am attempting to refresh a listview after I change the list items in it but it keeps failing with the message:

"Uncaught cannot call methods on listview prior to initialization; attempted to call method 'refresh'".

The list is an unordered list in a div with a data-role="dialog" attribute. The list has data-role="listview". After updating, if I call $('#theULInQuestion').listview('refresh'), I get the error message. What gives?

Thanks, Rob

Upvotes: 2

Views: 5845

Answers (1)

Jasper
Jasper

Reputation: 76003

There are a lot of page-events in the jQuery Mobile framework which makes it hard to determine which is the proper one to bind to. I bind to the pageshow event because by the time that event fires, the DOM is prepared (jQuery Mobile has initialized everything).

However whenever I am having issues with timing the refresh of a jQuery Mobile widget I check to see if it has been initialized and run the necessary code to either initialize or refresh the widget.

$(document).delegate('#my-dialog-id', '<page-event>', function () {
    var $the_ul = $('#theULInQuestion');
    //add your rows to the listview here
    $the_ul.append('<li>a row</li><li>another row</li>');
    if ($the_ul.hasClass('ui-listview')) {
        $the_ul.listview('refresh');
    } else {
        $the_ul.trigger('create');
    }
});

Each of the jQuery Mobile widgets have specific classes that are added to that type of widget. So you can check (after appending your rows) if the widget has the jQuery Mobile classes; if it does then refresh it, if it doesn't then initialize it.

Here is a jsfiddle: http://jsfiddle.net/jasper/urTeW/1/

Note that you can place the conditional statement to refresh/initialize anywhere in your code, it doesn't have to happen when a page-event fires.

Upvotes: 4

Related Questions