2016-01-13 47 views
0

我正在使用一個把手模板在我的導航欄上粘貼一些信息。信息來自Rails控制器通過AJAX調用。 AJAX,鑑於它是異步的,在模板接收到它的變量後完成,因此應該在AJAX調用中設置的變量從不這樣做。下面的代碼:我的手柄模板加載完成之前,如何才能完成AJAX調用?

export default { 
    name: "data-menu-item", 

    initialize: function(container) { 
    $(document).ready(function() { 
     var source     = $("#notification-menu-item").html(); 
     var template    = Handlebars.compile(source); 
     var user     = Discourse.User.current(); 
     var pro     = false; 
     var logged_user   = false; 
     var data_url    = ""; 


    $.ajax("/custom_group_names", { 
     type: 'GET' 
    }).done(function(res){ 
     if(res.custom_group_names){ 
     console.log(res.group_names); 
     for (var i=0; i < res.group_names.length; i++) { 
      // Agents, Brokers, ManagingBrokers, MortageBrokers, admins 
      if (res.group_names[i]["name"] === "Brokers" || res.group_names[i]["name"] === "ManagingBrokers" || res.group_names[i]["name"] === "MortageBrokers") { 
      console.log("groups were brokers, etc."); 
      pro = true; 
      data_url = "twobydev.com/brokerdashboard"; 
      } else if (res.group_names[i]["name"] === "admins" || res.group_names[i]["name"] === "Agents") { 
      console.log("groups were admin or agents"); 
      pro = true; 
      data_url = "twobydev.com/agentdashboard"; 
      console.log(pro); 
      console.log(data_url); 
      } 
     } 
     } 
    }); 

     if(user) { 
     logged_user = true; 
     if(user.total_unread_notifications > 0) { 
      new_notification_class = "new-notifications" 
      notification_count = "(" + user.total_unread_notifications + ")"; 
     } 
     } 

     var html = template({pro: pro, logged_user: logged_user, data_url: data_url}); 
     $('body').prepend(html); 
    }); 
    } 
} 

logged_user被設置是因爲它是Ajax調用之外,但是,我需要prodata_url被設置爲好。任何意見或幫助非常感謝!

回答

1

你只需要動這...

if(user) { 
    logged_user = true; 
    if(user.total_unread_notifications > 0) { 
     new_notification_class = "new-notifications" 
     notification_count = "(" + user.total_unread_notifications + ")"; 
    } 
} 

var html = template({pro: pro, logged_user: logged_user, data_url: data_url}); 
$('body').prepend(html); 

done函數中。

+1

不是一個好主意。現在已被棄用,瀏覽器廠商正在向控制檯投擲警告。這一直是一個不好的做法,因爲它阻止了用戶界面 – charlietfl

+1

@charlietfl Obvs不好的做法,但不知道它被棄用,所以公平點...刪除了異步選項;)注意,他還需要移動他的'如果(用戶){...}代碼塊在'done'裏面也是對的? – ann0nC0d3r

+0

是的,可能應該......我爲了展示概念而沒有完全重寫 – charlietfl

1

移動模板加工成Ajax回調

function processTemplate(){ 
    var html = template({pro: pro, logged_user: logged_user, data_url: data_url}); 
     $('body').prepend(html); 
} 

$.ajax({ 
    ..... 

}).done(function(res){ 
    /* existing processing code */ 

    // now process template 
    processTemplate() 
}); 
+0

這個伎倆! – stevenpslade

相關問題