尝试从节点服务器实现登录功能。我能够将骨干模型的请求发送到节点服务器。节点服务器调用另一个站点并从另一个站点获取响应。
现在如果登录成功,则应显示另一页面的响应。但如果登录失败,登录页面应显示错误消息。
的型号:
var LoginModel = Backbone.Model.extend({
url:'http://localhost:3000/login',
defaults: {
email:"",
password:""
},
parse: function(resp) {
console.log('Model: Got the response back');
return resp;
},
login: function() {
console.log('Model: Login function:'+JSON.stringify(this));
this.save(
{}, {
success: function(resp) {
console.log('success'+JSON.stringify(resp));
},
error: function(error) {
console.log('error: '+JSON.stringify(error));
}
});
console.log('Model: Got the response back:');
}
});
var loginModel = new LoginModel();
查看:
var LoginView = Backbone.View.extend({
url: 'http://localhost:3000/login',
template:_.template('<div class="form-signin">'+
'<h2 class="form-signin-heading">Please sign in</h2>'+
'<input type="text" id="email" class="form-control" placeholder="Email address" required="" autofocus="">'+
'<input type="password" id="password" class="form-control" placeholder="Password" required="">'+
'<button id="loginBtn" class="btn btn-lg btn-primary btn-block" >Sign in</button>'+
'</div>'),
events: {
"click #loginBtn":"login"
},
initialize: function() {
this.model.on('change', this.render, this);
},
render: function() {
var attributes = this.model.toJSON();
this.$el.html(this.template(attributes));
},
login: function() {
console.log('view signIn');
this.model.set({
"email": $('#email').val(),
"password": $('#password').val()
});
this.model.login();
}
});
var loginView = new LoginView({model: loginModel});
loginView.render();
$(".container").append(loginView.el);
注意:我是骨干新手并阅读路线。对我来说不太清楚。
答案 0 :(得分:0)
Backbone.Router 提供了路由客户端页面的方法
因此,在您的情况下,您的代码应如下所示:
var LoginModel = Backbone.Model.extend({
url:'http://localhost:3000/login',
defaults: {
email:"",
password:""
}
}
查看强>
var LoginView = Backbone.View.extend({
el: '.container'
template:_.template('...'),
events: {
"click #loginBtn":"login"
},
initialize: function() {
this.listenTo(this.model, 'change', this.render);
},
render: function() {
var attributes = this.model.toJSON();
this.$el.html(this.template(attributes));
},
login: function() {
console.log('view signIn');
this.model.set({
"email": $('#email').val(),
"password": $('#password').val()
});
console.log('Model: Login function:'+JSON.stringify(this.model));
this.model.save(
{}, {
success: function(resp) {
console.log('success'+JSON.stringify(resp));
},
error: function(error) {
console.log('error: '+JSON.stringify(error));
}
});
console.log('Model: Got the response back:');
}
});
<强>路由器强>
var Router = Backbone.Router.extend({
routes : {
"": "home",
"login" : "login"
},
home: function() {
// your home page
}
login: function() {
var loginModel = new LoginModel();
var loginView = new LoginView({model: loginModel});
loginModel.fetch();
}
})
new Router();
Backbone.history.start();