Javascript 具有持久数据的主干持久视图
我有一个导航栏,它几乎是我的web应用程序中唯一的一个持久性模板,无论路径如何,它总是在那里 在导航栏中,如果用户未登录,我会显示一个登录链接,如果用户已登录,我会显示他们的姓名,问题是我无法让导航保持其状态。使用登录名Javascript 具有持久数据的主干持久视图,javascript,backbone.js,backbone-views,Javascript,Backbone.js,Backbone Views,我有一个导航栏,它几乎是我的web应用程序中唯一的一个持久性模板,无论路径如何,它总是在那里 在导航栏中,如果用户未登录,我会显示一个登录链接,如果用户已登录,我会显示他们的姓名,问题是我无法让导航保持其状态。使用登录名 runLogin: function(e) { e.preventDefault(); var element = $(e.currentTarget), self = this; $.when($.ajax({ u
runLogin: function(e) {
e.preventDefault();
var element = $(e.currentTarget),
self = this;
$.when($.ajax({
url: 'http://app-api.dev/api/oauth/access_token?grant_type=password&client_id=1&client_secret=xyz',
method: 'POST',
data: element.serialize(),
dataType: 'json',
success: function(data) {
// Set the cookie, this will need to be sent in every singal request going foward.
$.cookie('access_token', data.access_token);
// So we have the access token we use this to populate our user details
},
error: function(response) {
// We can build a universal error view that would be quite and pretty easy to do.
}
})).done(function() {
$.ajax({
url: 'http://app-api.dev/api/users/me',
dataType: 'json',
method: 'GET',
success:function(user) {
self.model.set(user);
self.launchDashboard();
}
});
})
},
launchDashboard: function() {
localStorage.setItem('user', '');
localStorage.setItem('user', JSON.stringify(this.me));
App.Routes.Application.navigate('dashboard', { trigger: true } );
}
基本上,我登录,从API请求我的详细信息,并使用这些信息来设置模型,我正在设置的模型已经传递到导航视图中,并且有一个更改侦听器
showUserDetails: function() {
this.loggedInUserMenu = new App.Views.navigationViewLoggedIn({
model : this.model
});
},
上面是这个,
App.Views.navigationViewLoggedIn = Backbone.View.extend({
el: '.navbar-right',
template: _.template( $('#tpl-navigation-logged-in').html() ),
events: {
},
initialize: function() {
this.render();
},
render: function() {
this.$('.li-login').replaceWith( this.template({
user: this.model.toJSON()
}));
}
})
路由器
成功登录后,loggedInNavigation为visisble,我位于app-client.dev/dashboard。但是,如果我导航到'app-client.dev/groups,我将丢失loggedInNavigation,它将恢复为只显示登录
为什么?
===编辑我已经附加了创建主导航的方法,它是在路线初始化时完成的。进行视图更新的方法与前面代码中的方法相同,登录设置导航视图中的模型,侦听更改==请将路由器和一段代码连接到更新页面内容的位置好吗?完成。请参见编辑。谁拥有并启动runLogin方法?用户触发runLogin。它位于由表单提交触发的loginView中。
initialize: function() {
Pops.Models.AuthUser = new Pops.Models.User;
this.navigation_bar = new Pops.Views.navigationView({
model: Pops.Models.AuthUser
});
},