Backbone: Navigating to next page after successful response from node server - javascript

Trying to implement Login functionality from the Node server. I am able to send the request from backbone model to node server. Node server calls another site and get the response back from another site.
Now if the login is successful, another page should display with response. But if the login turns unsuccessful, login page should display the error message.
Model:
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();
View:
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);
Note: I am new to backbone and read about routes. It was not very clear to me.

Backbone.Router provides methods for routing client-side pages
So in your case, your code should look like :
var LoginModel = Backbone.Model.extend({
url:'http://localhost:3000/login',
defaults: {
email:"",
password:""
}
}
View
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:');
}
});
Router
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();

Related

backbone events triggered arbitrary number of times

New to backbone, I'm approaching it with trivial example but i'm stuck on events triggering.
In my page i GET some data from the server and initialize a view with them.
Then i can change the data through a form, they are saved to the server and the template is updated soon after with the new data. The data are fetched, saved and the view is updated but I can see through the console that the render function is called sometime twice, sometime even 4 times! And the call to the server, too, is made up to for time as GET, PUT, GET, GET.
What am i doing wrong?
<script type="text/x-handlebars-template" id="modelTpl">
<ul>
<li><strong>Nome:</strong> {{nome}}</li>
<li><strong>Cogome:</strong> {{cognome}}</li>
</ul>
<input type="text" id="nome" />
<input type="text" id="cognome" />
<a id="changeBtn">Modifica</a>
</script>
Model = Backbone.Model.extend({
urlRoot: 'server/model.php/model',
defaults: {
nome: "",
cognome: ""
}
});
var model = new Model({id: 1});
View = Backbone.View.extend({
el: '#wrapper',
template: Handlebars.compile($('#modelTpl').html()),
events: {
"click #changeBtn": "change"
},
initialize: function(){
this.render();
this.listenTo(this.model, "change", this.render);
},
render: function(){
console.log('render');
var self = this;
this.model.fetch({
error: function(model, response, options) { },
success: function(model, response, options) {
var data = model.toJSON();
self.$el.html(self.template(data));
}
});
return this;
},
change: function() {
var n = this.$('#nome').val();
var c = this.$('#cognome').val();
this.model.save({ nome: n, cognome: c }, {
error: function(model, response, options) { },
success: function(model, response, options) { }
});
}
});
var view = new View({ model: model });
I know its late to answer this question now. However it may help other, so try _.debounce
this.change = _.debounce(this.change, 300);

Backbone fetch producing 404 error

I have the following backbone model node that I am trying to use to fetch data from the server but at the moment I get a 404 error, I have checked my files and they seem to be correct
var app = app || {};
app.NotesModel = Backbone.Model.extend({
url:'/usernotes',
defaults: {
username:'',
email:'',
about:'',
editorNote:''
}
});
app.NotesView = Backbone.View.extend({
el:'#notes',
events: {
'click #save': 'save'
},
template1: _.template($('#about').html()),
template2: _.template($('#facts').html()),
initialize: function() {
app.NotesModel = new app.NotesModel({});
var email = $('#data-user').text();
app.NotesModel.fetch({data: {email: email},type:'GET' });
this.render();
},
render: function() {
},
This is what the route file looks like
app.get('/account/usernotes/', require('./views/account/usernotes/index').init);
app.get('/account/usernotes/:email', require('./views/account/usernotes/index').find);
and the functions for the routes
'use strict';
exports.init = function(req, res){
if (req.isAuthenticated()) {
//console.log(req.user.email);
res.render('account/usernotes',
{ data : {
user : req.user.email
}
});
}
else {
res.render('signup/index', {
oauthMessage: '',
oauthTwitter: !!req.app.config.oauth.twitter.key,
oauthFacebook: !!req.app.config.oauth.facebook.key,
oauthGoogle: !!req.app.config.oauth.google.key
});
}
};
exports.find = function(req,res) {
console.log('here');
console.log(JSON.stringify(req));
}
Doing the console.log() doesn't give me any output at all.
Here is a similar question.
Try this:
app.NotesModel.fetch({data: $.param({email: email}) });
or this:
app.NotesModel.fetch({data: {email: email}, processData: true });

Backbone: Navigate does not hit the specified route

Calling navigate after saving a model.
this.model.save({},{
success: function(model, response, options){
Backbone.history.navigate('getCampaigns', {tigger: true});
}
});
But it never hits the specified route.
Route class
var Router = Backbone.Router.extend({
routes: {
"":"home",
"login":"login",
"getCampaigns":"getCampaigns"
},
start: function() {
Backbone.history.start({pushState:true});
},
home: function() {
var loginView = new LoginView({model: loginModel});
loginView.render();
$(".container").append(loginView.el);
},
login: function(event) {
event.preventDefault();
},
getCampaigns: function() {
this.dashboardList.fetch();
$('.container').html(this.dashboardListView.render().el);
}
});
var app = new Router();
app.start();
You have an error in your code :
Backbone.history.navigate('getCampaigns', {trigger: true}); // not {tigger: true}

Backbone unwanted route redirect on webkit

I have an unwanted route redirect after authentification
My base url is
http://127.0.0.1:8020/VT/
If the user isn't logged in localstorage, i'll load the login view.
The main menu view render correctly if the login succeed,
I have this unwanted automaticaly redirection to
http://127.0.0.1:8020/
This only happen on webkit browser. (haven't tried on IE)
Router = new MainRouter();
Backbone.history.start({
pushState: false,
root: "/VT/"
});
var MainRouter = Backbone.Router.extend({
routes: {
"": "login",
"login": "login",
"main": "mainMenu"
},
showView: function(view){
if (this.currentView){
this.currentView.close();
}
this.currentView = view;
this.currentView.render();
$('#wrapper').html( this.currentView.el );
},
login: function(){
var result = app.session.isLoggedIn();
if(result == true){
this.navigate('main', {trigger: true, replace: true});
}
else{
var loginView = new LoginView();
this.showView( loginView );
}
},
mainMenu: function(){
var mainMenu = new MainMenuView();
this.showView( mainMenu );
},
});
var LoginView = Backbone.View.extend({
name: "Login",
el: $('#page-login'),
initialize : function() {
this.template = _.template( app.get("tpl/nav/login.html") );
this.clearStatusBar();
},
render: function(){
var renderedContent = this.template();
$(this.el).html(renderedContent);
return this;
},
events: {
"click input[type=submit]": "loginAction"
},
validate: function(){
// some validation code
},
loginAction: function(){
if( this.validate() ){
app.router.navigate('main', {trigger: true, replace: true});
}
else{
alert('Login failed');
}
},
});
I can't figure it out why. Any suggestions ?

Login Handling in Backbone.js

i need a very simple login system for my web application with backbone.js
Workflow:
App Start -> LoginView -> When Logged In -> App
Here is my solution. What can i do better?
Login Status Model:
window.LoginStatus = Backbone.Model.extend({
defaults: {
loggedIn: false,
userId: null,
username: null,
error: "An Error Message!"
},
initialize: function () {
_.bindAll(this, 'getSession', 'setStorage');
},
getSession: function (username, password) {
var tmpThis = this;
$.getJSON('http://requestURL.de/getSession.php?username=' + username + '&password=' + password, function(data) {
if (data != null) {
tmpThis.setStorage(data.id, data.username);
$.mobile.changePage("#home");
}
});
},
setStorage: function(userId, username) {
localStorage.setItem("userId", userId);
localStorage.setItem("username", username);
this.set({ "loggedIn" : true});
}
});
Here is my Login View:
window.LoginView = Backbone.View.extend({
el: $("#login"),
initialize:function () {
this.render();
},
events: {
"click input[type=submit]": "onSubmit"
},
onSubmit: function(event) {
var username = $(this.el).find("#user-username").val(),
password = $(this.el).find("#user-password").val();
this.model.getSession(username, password);
return false;
},
render:function () {
if (this.model.get("loggedIn")) {
var template = _.template( $("#login_template").html(), {} );
} else {
var template = _.template( $("#login_template").html(), { "error" : this.model.get("error") } );
}
$(this.el).html( template );
}
});
My suggestion to you is making the login outside the backbone app and only after a success login process let them access the "single page app"
You can refer to this backbone project which does the login request using POST method. https://github.com/denysonique/backbone-login

Categories