Skip to content

Instantly share code, notes, and snippets.

@jonhargett
Created September 5, 2012 20:39
Show Gist options
  • Save jonhargett/3644368 to your computer and use it in GitHub Desktop.
Save jonhargett/3644368 to your computer and use it in GitHub Desktop.
Backbone View that checks to see if you are logged in and if not display a login form.
var LoginForm = Backbone.View.extend({
className : 'divLogin',
initialize : function() {
this.dialogContent = '<div class="field"><label for="username">User Name:</label> <input type="text"' +
'name="username" id="username" value="" />' +
'</div><div class="field"><label for="password">Password:</label>' +
'<input type="password" name="password" id="password" value="" /></div>';
this.render();
},
firstTry: true,
events : {},
login : function() {
var data = {
'User' : {
'username' : $('#username').val(),
'password' : $('#password').val()
}
};
$.ajax({
type : "POST",
url : this.options.serviceURL,
dataType : 'json',
async : false,
data : data,
context : this,
success : function(data, textStatus, jqXHR) {
if (data.success !== true) {
this.showDialog();
if (!this.firstTry){
alert(data.message);
}
this.firstTry = false;
} else {
$(this.el).dialog("close");
}
},
error : function(jqXHR, textStatus, errorThrown) {
this.firstTry = false;
if (jqXHR.status == '401') {
this.showDialog();
} else {
alert(textStatus);
}
}
});
},
showDialog: function(){
$(this.el).html(this.dialogContent).hide().dialog({
modal : true,
buttons : {
"Submit" : $.proxy(function() {
this.login();
}, this),
Cancel : $.proxy(function() {
$(this.el).dialog("close");
}, this)
}
});
},
render : function() {
this.login();
return this;
}
});
var login = new LoginForm({
serviceURL: 'service/users/login'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment