David
David

Reputation: 555

jQuery Mobile - Going directly to hash URL causes dynamic elements to fail

I'm running into an issue where dynamic elements on a page are updated on "pageshow". This works great if the user goes directly to the url or navigates to it from somewhere else in the site. The problem is if I go directly to that page, or refresh it (eg: mydomain.com/#somepage.html) it fails and I get the error:

Uncaught cannot call methods on selectmenu prior to initialization; attempted to call method 'refresh'

I am calling the refresh in a function that populates select lists with ajax content.

I've looked at using another event instead of pageshow but none seem appropriate.

Here are the relevant bits of code:

        //attach all listeners on dynamically loaded pages here
    $('[data-role=page]').live('pageshow', function(event, ui){ 
        //do stuff (get data, get select options, index of current selected
            $('select.myselect').fillSelect(itemsArray,indexofSelected);

    ...
    )}; //pageshow

This is the function I sue to populate the select:

$.fn.fillSelect = function (items,index){
    //generically fills a select list - requires an array and target element optional index of selected element
    this.find('option').remove();
    var options = "";
    for (var i = 0; i < items.length; i++) {
            var selected = (index == i) ? 'selected="selected"' : "" ;
            options += '<option '+selected+'value="'+items[i]+'">'+items[i]+'</option>';
    } 
    //assembling html first cause appends are expensive
    this.append(options).selectmenu('refresh', true);

    return this;
}

Again this is specific to going directly to hash urls but works perfectly otherwise.

Upvotes: 1

Views: 1320

Answers (1)

naugtur
naugtur

Reputation: 16905

That's because you bind the pageshow event too late. It's already shown. To be sure it works put your bits of code in a file loaded before jquery mobile and make sure you don't wait for DOMready to call $('[data-role=page]').live('pageshow' ... live is the only thing that will work even if the selector gets you an empty result due to not loaded DOM.

Upvotes: 2

Related Questions