I’m a little unsure about how to set up functionality for a login/logout control in Backbone.js.
This is what I’m thinking, but I’m not sure if this is ok or if there are problems with this architecture:
- The
Modelis the current user. If the model gets anHTTP 404response when doing afetch(), then the “current user” should be an anonymous user. If not, then theModelholds the current user’s information. - The
View:- If the current user is “anonymous”, it shows input boxes for a user name and password; and a “login” button.
- If the current user is a valid user, the view shows the current user’s username and a “logout” button.
I’m not sure what to do with the model when the “login” and “logout” buttons are pressed. Should the logging in and logging out be done through the model’s fetch() functionality, or should those actions trigger a different POST request whose successeful result either populates the Model or asks the Model to do another fetch()?
Any input is appreciated, thanks so much!
This may be a bit unexpected to what you’ve asked but this is how I’ve pulled it off:
I’m not sure why do you need the model per se and I’m confused about how you are using it. Thus I’m not able to frame my answer with the “model” in mind.
So here’s how I did it:
In the view: just textboxes for login/logout.
On clicking “login” send a POST request to the server with username/password (hopefully not in clear text 🙂
If the server’s response is 200 change
window.locationto the target page you wish to see else display “invalid username/password” (of course the “next” page or any other page in the application should check to see if the user is logged in. If not, show login page).This is the simplest solution IMHO. I’m not sure why you need to have the model for the user? Is that “after” logging in? Then you can just generate and keep it or have it sent as part of the 200 response above. But the model won’t be persisted across the page change. Better to recreate the model on the ‘next’ page so to speak.
(I’m assuming a page change and NOT a page load as in
$.load– if the latter, then you can always reuse the model).Hope this makes sense. If not, could you please clarify the intent of the model and maybe I’ll be able to update my answer accordingly.