在我的车把模板完成加载之前,如何才能获得未完成的AJAX调用?

时间:2016-01-13 19:24:26

标签: javascript jquery ruby-on-rails ajax handlebars.js

我正在使用把手模板在我的导航栏上粘贴一些信息。信息来自Rails控制器通过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。任何建议或帮助都非常感谢!

2 个答案:

答案 0 :(得分: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 :(得分: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()
});