persistence

& partials

Class overview

  • Homework Questions
  • Persistence Strategies
  • localStorage
  • Handlebars Partials
  • Homework Exercises

PERSISTENCE STRATEGIES

  • Problem: Browsers cannot access the local file system directly
  • Solutions:
    • Cookies
    • Store state on the server
    • Local Storage

LOCALSTORAGE

  • Browser based data storage solution
  • Roughly 5-10mb depending on the browser
  • Key-Value store, so for complex objects or arrays, serialized into a JSON string
  • Domain specific, so it is "fairly" safe, but don't store sensitive data
 window.localStorage;
 //set something to localStorage
 window.localStorage.cart = JSON.stringify(["1","2"]);
 window.localStorage.userName = "JimBob";
 //get from localStorage
 var cartArray = JSON.parse(window.localStorage.cart);
 

HANDLEBARS PARTIALS

  • Sub-templates
  • Gets the same object from where it is called
  • Registered in the global Handlebars object
  • Looks just like a regular template
 //assuming a template called addButtonTemplate exists in the DOM
 //register a partial before calling a template where it is used
 Handlebars.registerPartial('addButton', $('#addButtonTemplate').html());

 //Using a partial in a template
 //append a '>' character before the partial name
 <div class="likeButton" data-item-id="{{id}}">
     {{#if inCart}}
          {{> removeButton}}
     {{else}}
          {{> addButton}}
     {{/if}}
 </div>

cool js thing for the day

Exhaustive resource for learning JavaScript

AJS Lecture 12: Persistence & Partials

By Ryan Lewis

AJS Lecture 12: Persistence & Partials

  • 619