2011-12-15 69 views
0

如何讓jquerymobile推遲執行mobileinit直到加載DOM?如何讓mobileinit暫停執行,直到json加載爲止

我試圖使用模板& JSON在飛行中創建頁面。我的問題是,JSON花費太長時間來加載和jquerymobile已完成mobileinit事件!

示例代碼:

$(document).bind("mobileinit", function(){ 
     console.log("mobileinit"); 

     // get JSON & set template... should wait until this is done! 
     getData(); 

     //SWIPE SWIPE 
     $('div[data-role="page"]').live("swipeleft", function(){ 
      var nextpage = $(this).next('div[data-role="page"]'); 
      // swipe using id of next page if exists 
      if (nextpage.length > 0) { 
       $.mobile.changePage(nextpage, 'slide'); 
      } 
     }); 
     $('div[data-role="page"]').live("swiperight", function(){ 
      var prevpage = $(this).prev('div[data-role="page"]'); 
      // swipe using id of next page if exists 
      if (prevpage.length > 0) { 
       $.mobile.changePage(prevpage, 'slide', true); 
      } 
     }); 
     console.log("mobileinit done"); 
    }); 
+0

你能告訴我們'getData()`的代碼嗎? – graphicdivine 2011-12-15 09:19:30

回答

1

success函數中您可以使用jQuery.Deferred()來完成此操作。

// Let's assume that getData returns a deferred. 
function getData() { 
    return $.get('your/request/url'); 
}); 

$(document).bind("mobileinit", function() { 
    // Now you can use the deferred returned from the getData function. 
    getData().done(function() { 
     //SWIPE SWIPE 
     $('div[data-role="page"]').live("swipeleft", function() { 
      var nextpage = $(this).next('div[data-role="page"]'); 
      // swipe using id of next page if exists 
      if (nextpage.length > 0) { 
       $.mobile.changePage(nextpage, 'slide'); 
      } 
     }); 
     $('div[data-role="page"]').live("swiperight", function() { 
      var prevpage = $(this).prev('div[data-role="page"]'); 
      // swipe using id of next page if exists 
      if (prevpage.length > 0) { 
       $.mobile.changePage(prevpage, 'slide', true); 
      } 
     }); 
    }); 
} 
1

假設getData()功能包含$.ajax通話,你需要把初始化代碼的復位getData()$.ajax呼叫

相關問題