Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var userModel_pd = Backbone.Model.extend({
- // Default attributes for the todo item.
- defaults: function() {
- return {
- token: "Token here",
- name: "Name here",
- householdId: "Household ID here",
- householdName: "Household name",
- expiration: 0, // need to bind a the log-in event to this object changing to !0
- structure: {},
- id: 1
- };
- },
- //as above, need to bind a the log-in event to this object changing to !0
- //Set attributes if passed
- initialize: function(structure_) {
- if (structure_.success == true){
- this.setAndSave(structure_);
- }
- },
- validCookie: function() { //returns true if cookie hasn't expired and value matches that of userModel, else returns false and reboot() the model
- if($.cookie('user')) {return true;} else {this.reboot(); return false;}
- },
- reboot: function() { // Reset.
- this.save({token: "Token here", name: "Name here", expiration: 0, householdId: "Household ID here", structure: {}});
- console.log('rebooting model');
- },
- setAndSave: function(structure_) {
- this.set({name: structure_.currentUser.username, expiration: structure_.expiration, householdId:structure_.currentUser.household.id, householdName: structure_.currentUser.household.name, token: structure_.token, structure: structure_ });
- this.save();
- }
- // **** the change event from reboot should trigger a rerendering in the AppView of sidebar-view and topbar-view
- });
- //COLLECTION: saveduser is used to persist the userModel_pd instance to local storage
- var savedUser = Backbone.Collection.extend({
- model: userModel_pd,
- // Save the user info under the `blue` namespace.
- localStorage: new Store("blue-backbone")
- });
- // Create our global User-holder - necessary to store the model to Local Storage
- var savedUser_instance = new savedUser;
- //VIEW: sessionView -- interfaces with DOM inputs, handles the cookie , etc.
- var SessionView = Backbone.View.extend({
- el: $(".login_box"), //Binding to HTML skeleton //(template not needed here), bind to HTML //template: _.template($('#session-template').html());
- initialize: function() {
- // Binding View to DOM Elements // note to self: used to be in initialize function
- this.name = this.$('#nameLogin');
- this.password = this.$('#passwordLogin');
- this.loginButton = this.$('#imgLogin');
- this.logoutButton = this.$('#imgLogout');
- //Look to local storage for an existing user model
- savedUser_instance.fetch();
- // If the userModel's attributes are changed, this (session) View will rerender
- //savedUser_instance.bind('add', this.render, this); //this.model.bind('change', this.render(), this);
- //savedUser_instance.get(1).bind('change', this.render(), this);
- this.model.bind('change', this.render(), this);
- console.log('before fetch'); console.log('after fetch'); console.log("collection length " + savedUser_instance.length);
- // If the savedUser collection does not have a userModel, add one
- if (savedUser_instance.length == 0){
- console.log('instantiate user model');
- var userModelglobal = new userModel_pd;
- savedUser_instance.add(userModelglobal);
- }
- //console.log("the sessionView's model token is " + this.model.get('token'));
- // If a user model exists, check for a valid cookie
- if (savedUser_instance.length){
- console.log('checking cookie ' + savedUser_instance.get(1).validCookie());
- if (!savedUser_instance.get(1).validCookie()){ // If model does not return valid cookie, reset model
- savedUser_instance.get(1).reboot(); // !!!! This triggers a 'change' event, which causes the session View to rerender (see above bound event)
- } }
- this.render();
- },
- events: // 1.) clicking log in (hitting enter too) calls the ApiCommand to set cookie 2.) Logging out rerenders View
- {
- "keypress #nameLogin": "pushCredsOnEnter",
- "keypress #passwordLogin": "pushCredsOnEnter",
- "click #imgLogin": "pushCreds",
- "click #imgLogout": "unsetSession"
- },
- render: function() { // 1.) acknowledge a valid cookie by moving the View to the left
- console.log('rendering session View');
- if (savedUser_instance.get(1).validCookie()){
- //replaceable DOM references
- //ACTION SHOULD OCCUR FROM THE CHANGE EVENT, NOT MANUALLY STIPULATED HERE
- console.log( savedUser_instance.get(1).get('name') +'has logged-in');
- $('#imgLogout').show('slow'); //this.logoutButton.show('slow');
- //the below animation is a (non-final) demonstration of state change (having logged in)
- //this.$el.hide(); // works
- //$('.login_box').hide();
- //$('.login_box').css({"position":"relative","right":"100px"}); // animate({"position":"relative","right":"100px"})
- //TODO **** stub: render a checkmark image - perhaps in a jquery-esque manner
- console.log('again, were here');
- } else {
- console.log('original rendering settings');
- $('#imgLogout').hide('hide');
- this.$el.animate({"position":"relative","right":"0px"});}
- },
- // If you hit return in either input field, it will attempt to log you in (by pushing credentials)
- pushCredsOnEnter: function(e) {
- console.log('pushing creds');
- if (e.keyCode != 13) return;
- if (!this.name.val() && !this.password.val()) return;
- this.pushCreds();
- this.name.val('');
- this.password.val('');
- },
- //Take returned JSON, convert it to a Javascript function, set a cookie with those values
- pushCreds: function(){
- var dataUnique_ = command_center("log_in", {'username_': this.name.val(), 'password_': this.password.val()});
- console.log('Callback object from pushCreds ' + dataUnique_);
- this.parse_set_cookie(dataUnique_); //SET TWO COOKIES, USER (VALUE = USERNAME), SESSION (VALUE = TOKENID)
- savedUser_instance.get(1).setAndSave(dataUnique_); //The set() will trigger a change event, which will call this View's render function
- //commented out, because resetting model *should* have been bound to re-rendering view
- //this.render();
- dataUnique_ = "";
- this.render();
- },
- //Take returned JSON, convert it to a Javascript function, set a cookie with those values
- unsetSession: function(){
- $.cookie('user', null);
- $.cookie('session', null);
- savedUser_instance.get(1).reboot(); //which, again, should trigger change event which will handle rerendering
- //commented out, because resetting model should be bound to re-rendering view
- //this.render();
- },
- parse_set_cookie: function (jsonFromPHP) {
- console.log('Json from the Proxy ' + jsonFromPHP);
- //SETTING TWO COOKIES, MIMICKING THE GREENHOME API PLAYGROUND BEHAVIOR
- var thedate=new Date(jsonFromPHP.expiration);
- myExpiration = thedate.getUTCMilliseconds();
- myUsername = jsonFromPHP.currentUser.username;
- myToken = jsonFromPHP.token;
- console.log(myUsername);
- console.log(myToken);
- console.log(myExpiration);
- $.cookie('user', myUsername, {'expires':myExpiration}); // , {'expires':myExpiration}
- $.cookie('session', myToken, {'expires':myExpiration}); // , {'expires':myExpiration}
- console.log('Cookie Set ' + $.cookie('user'));
- }
- });
- //VIEW ****
- // show() or hide() sessionView div. - to be replaced by animation eventually
- var appView = Backbone.View.extend({
- initialize: function() {
- console.log('instantiating the session View from the App View');
- //Instantiate the SessionView()
- var sessionView_instance = new SessionView({model: userModel_pd});
- }
- });
- var blueApp = new appView;
Add Comment
Please, Sign In to add comment