Blog

12Dec
2011
jQuery Mobile Control Refresh Gotcha

jQuery lets you manually manipulate controls like lists. For example, you can do something like this to add an item to a list:

view plain print about
1$('#myList').append('<li>Some text</li>');

In jQuery Mobile, if you manually update lists like that, then when you are done you must force the list to refresh so that formatting and styles are applied. To do this, just use:

view plain print about
1$('#myList').listview('refresh');

But, there is one gotcha you should be aware of. jQuery Mobile apps are usually comprised of pages, each defined with a <div data-role="page">, and often with multiple in the same .html file. jQuery (and thus jQuery Mobile) lets you manipulate any controls in your page, so you can append or change controls in a page not currently being displayed. But, the .listview('refresh') call? That will only work if the control is on the currently displayed page. If you try to .listview('refresh') a control on a page that is not displayed, you'll see this error:

view plain print about
1Uncaught cannot call methods on listview prior to initialization; attempted to call method 'refresh'

So, if you do need to update controls on a not currently displayed page, remember to load that page before triggering the refresh.

Related Blog Entries

Comments (4)



  • Mike

    Hi Ben,
    This is one question that always comes up at the JQM forum so its good to see it spelled out, one thing I would mention though is that while you can have multiple pages in an HTML (multi page template)

    JQM recommends to use the single page template as it is cleaner and more lightweight.

    I know its a little nit picky but I think its important to point out because programs like DW 5.5 give you the basic template that has the page ID's in it and while it works to do it that way I think its setting developers up to create a web app outside of the recommended method of JQM.

    Anyhow great post!

    #1Posted by Mike | Dec 15, 2011, 12:25 PM
  • Ivan R.

    Genius!

    #2Posted by Ivan R. | Feb 29, 2012, 12:57 AM
  • Isaac Lim

    Thank you so much for writing this article! It helped me soo much with debugging my app for school! Thanks!!

    #3Posted by Isaac Lim | Dec 6, 2012, 07:42 PM
  • Craig Laparo

    I'm running into this problem as well. You said (and I had suspected) I need to "load" the hidden pages before updating their controls.

    How exactly do you recommend doing this? I've tried all kinds of things, and searches have been fruitless. Thanks in advance.

    #4Posted by Craig Laparo | Jan 8, 2013, 05:53 PM