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.

Creating The 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);

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.

Reloading The Existing Record

To load the existing record and re-use it, I need to do a couple of things:

  1. Have the datasource read the underlying data store
  2. Check for the existence of a credentials record

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;
    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);

    // ensure the data (new or updated) is persisted

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

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, NodeJS, .NET and more. Derick blogs, produces screencasts, tweets as @derickbailey and provides support and assistance for JavaScript, BackboneJS,MarionetteJS and much more around the web.

Related Posts


Comments are disabled in preview mode.