好。我想在路由器的home操作中使用model的“loggedIn”属性来检查用户是否已登录。这是我的代码。 请检查路由器的主页操作。
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
答案 0 :(得分:1)
您可以在初始化时创建它,然后在任何地方使用它。
initialize: function() {
this.loginStatus = new LoginStatus();
},
home: function() {
if (this.loginStatus.get('loggedIn')
// render dashbord template
else
// render login template
},