So,继上篇Nodejs Backbone RESTify 创建一个前后端分离的用户登 之后,我们简单地说说,如何用Backbone创建一个简单的用户登陆。
首先我们需要创建一个login.html
<form>
<label>User</label>
<input type='text' id="username" name='username' placeholder="Username"></td>
<label>Password</label>
<input type="password" id="password" name="password" placeholder="Password">
<button type="submit" name="submit" id="login">Sign in</button>
</form>
复制一个简单的View.js,创建一个简单地events。
define([
'jquery',
'underscore',
'mustache',
'text!/templates/login.html',
'js/User',
'js/UserSession'
],function($, _, Mustache, loginTemplate, User, UserSession){
'use strict';
var user = new User();
var LoginView = Backbone.View.extend ({
el: $("#content"),
initialize: function(){
},
events: {
"click #login": "login"
},
login: function(event){
event.preventDefault();
var userInfo = {
name: $('#username').val(),
password: $('#password').val()
};
user.login(userInfo, function(){
UserSession.save({
name: userInfo.name,
accessToken: userInfo.name
});
window.app.navigate('userProfile', true);
});
},
render: function(){
this.$el.html(Mustache.to_html(loginTemplate, {data:"data"}));
}
});
return LoginView;
});
这样当我们点击id为login的按钮就会促发login函数,在login函数中会读取name和password验证,成功的话然后调用Usersession的save()
一个简单的User.login代码如下所示,
define([
'jquery',
'underscore',
'mustache',
'js/UserSession'
],function($, _, Mustache, UserSession){
'use strict';
function User(){
}
User.prototype.login = function(userObject, callback) {
var LoginAccount = Backbone.Model.extend({
defaults: {
name: null,
password: null
},
url: function() {
return 'http://localhost:8080/login/user';
}
});
var login = new LoginAccount({
name: userObject.name,
password: userObject.password
});
login.save({}, {
success: function(model, response) {
if(response.status === "success"){
var name = userObject.name;
UserSession.save({
"name": name,
"accessToken": response.accessToken
});
callback();
} else {
}
},
error: function(model, response) {
callback();
}
});
};
return User;
});
下面的代码是谷歌过来的,加了一点小小的修改
define([
'jquery',
'underscore',
'backbone',
'jquery-cookie'
],function($, _, Backbone){
'use strict';
var UserSession = Backbone.Model.extend({
defaults: {
'accessToken': null,
"userName": null
},
initialize: function(){
this.load();
},
authenticated: function(){
return !_.isEmpty($.cookie('accessToken'));
},
save: function(authHash){
$.cookie('name', authHash.name);
$.cookie('accessToken', authHash.accessToken);
},
load: function(){
this.userName = $.cookie('name');
this.accessToken = $.cookie('accessToken');
}
});
return new UserSession();
});
这里会在cookie在保存name和accessToken
如果用户不是登陆的话,就跳转到account/login
router.on('route:userProfile', function(action) {
console.log(UserSession);
if (UserSession.authenticated() == true) {
var userProfileView = new UserProfileView();
userProfileView.render();
} else {
router.navigate('account/login', true)
}
});
围观我的Github Idea墙, 也许,你会遇到心仪的项目