In my last post, I talked about storing user credentials from Everlive in localstorage. This gave me a nice way to keep a user logged in, between page refreshes. After having used this for a bit, I realized that I was adding new records to the local storage on every login. This was causing a problem because I wasn't getting the right credentials loaded all the time. Every time the wrong credentials were loaded, the app thought I was not logged in because the credentials were invalid. To fix this, I needed to fix my storage so that it always loaded a single record and saved that single record.
The original method that I posted in the previous post works well for creating a record in the datasource.
storeCredentials: function(creds){ // wrap the credentials in an observable var credentials = kendo.observable(creds); // set and store the credentials this.set("credentials", credentials); this.dataSource.add(credentials); this.dataSource.sync(); }
Every time the storeCredentials
method is called, a new record is
stored for the credentials. But this isn't enough. The code needs to be able to re-use
the same record when one already exists.
To load the existing record and re-use it, I need to do a couple of things:
If I don't have a credentials record, go ahead and run the above code to add one. But if I do have a credentials record, update the record with the new credentials.
storeCredentials: function(creds){ // read the data to see if there's a record this.dataSource.read(); var oldCreds = this.dataSource.view()[0]; // see if we have a valid record if (oldCreds && oldCreds.get("Id")){ // update the old record oldCreds.set("access_token", creds.access_token); oldCreds.set("principle_id", creds.principle_id); oldCreds.set("token_type", creds.token_type); } else { // no record found, so create a new one this.set("credentials", creds); this.dataSource.add(creds); } // ensure the data (new or updated) is persisted this.dataSource.sync(); }
Now when I call the storeCredentials
method, the existing credentials record will be used
if there is one. If there isn't one, a new one will be created.
About the Author
Derick Bailey is a Developer Advocate for Kendo UI, a developer, speaker, trainer, screen-caster and much more. He's been slinging code since the late 80’s and doing it professionally since the mid 90's. These days, Derick spends his time primarily writing javascript with back-end languages of all types, including Ruby,