2014-02-22 59 views
-1

好的。我想在路由器的home動作中使用模型的「loggedIn」屬性來檢查用戶是否登錄。這是我的代碼。 請檢查路由器的主頁操作。如何在backbone.js中檢查路由器中模型的屬性?

LoginStatus Model 
-------------------- 
window.LoginStatus = Backbone.Model.extend({ 
    defaults: { 
     loggedIn: false, 
     userId: null, 
     email: null, 
     error: "Error!" 
    }, 

    initialize: function() { 
     //_bindAll(this, 'getSession', 'setStorage'); 
    }, 

    getSession: function(email, password) { 
     var self = this; 
     var url = '../api/login'; 
     $.ajax({ 
      url:url, 
      type:'POST', 
      dataType:"json", 
      data: { 
       email: email, 
       password: password 
      }, 
      success:function (data) { 
       //console.log(["Login request details: ", data]);    
       if(data.error) { // If there is an error, show the error messages 
        $('.alert-error').text(data.error.text).show(); 
       } 
       else { // If not, send them back to the home page 
        self.setStorage(data.id, data.email); 
        Backbone.history.navigate("#dashboard", {trigger : true}); 
       } 
      } 
     }); 
    }, 

    setStorage: function(userId, email) { 
     //alert(userId); 

     localStorage.setItem("userId", userId); 
     localStorage.setItem("email", email); 
     this.set({ "loggedIn" : true}); 
    } 
}); 

Backbone Router 
--------------- 
window.Router = Backbone.Router.extend({ 

    routes: { 
     "": "home", 
     "login": "login", 
     "dashboard": "dashboard", 
    }, 

    initialize: function() { 

    }, 

    home: function() { 
     /*Here I want to check whether user is logged in or not something like 
      if (loginStatus.loggedIn) 
       render dashbord template 
      else 
       render login template 

      HOW CAN I WRITE ABOVE THING/LOGIC ? */ 

    }, 

    login: function() { 
     $('#container').html(new LoginView().render().el); 
    }, 

    dashboard: function() {  
     $('#container').html(new DashboardView().render().el); 
     $('#dynamic_css').attr('href','css/dashboard.css'); 
    } 

}); 

感謝,Jimit

回答

1

您可以創建它初始化,然後到處使用它。

initialize: function() { 
    this.loginStatus = new LoginStatus(); 
}, 

home: function() { 
    if (this.loginStatus.get('loggedIn') 
     // render dashbord template 
    else 
     // render login template 
}, 
相關問題