DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Data
  4. LocalStorage Example: Storing Previous Searches

LocalStorage Example: Storing Previous Searches

Raymond Camden user avatar by
Raymond Camden
·
Jul. 17, 12 · Interview
Like (0)
Save
Tweet
Share
7.04K Views

Join the DZone community and get the full member experience.

Join For Free

I've made it clear that I'm a huge fan of LocalStorage. While sitting in the Houston airport for many hours this week, I decided to whip up a little example that demonstrates one of the practical uses for this feature. I built a simple Ajax-based search page and then added LocalStorage as a way to remember your previous searches. This isn't anything special, but I think it's another good example of the feature. Let's begin by taking a look at the application before any use of LocalStorage.

The application makes use of Bootstrap, jQuery, and Handlebars, but for now, let's just focus on the JavaScript and the template:

<script>
    $(document).ready(function() {

      var source = $("#artResultsTemplate").html();
      var template = Handlebars.compile(source);

      $("#searchButton").on("click", function(e) {
        e.preventDefault();
        var search = $.trim($("#search").val());
        if(search === '') return;
        console.log("search for "+search);
        $.get("service.cfc?method=searchArt", {term:search}, function(res,code) {

          var html = template({results:res});
          $("#results").html(html);
        },"JSON");

      });
    });
    </script>

  <script id="artResultsTemplate" type="text/x-handlebars-template">
    <h1>Results</h1>
    {{#if results}}
      <ul class="thumbnails">
      {{#each results}}
        <li class="span3">
          <div class="thumbnail">
            <img src="{{image}}" width="260" height="180" title="{{name}}">
            <div class="caption">
              <h5>{{name}}</h5>
              <p>{{description}}</p>
              <p>Created by {{artist}} and selling for ${{price}}</p>
            </div>
          </div>
        </li>
      {{/each}}
      </ul>
    {{else}}
      <p>
      Sorry, no results.
      </p>
    {{/if}}
  </script>

You can see that I begin by compiling my Handlebars template (this is used for the results), and then I define my click handler for the search button. All the handler does is grab the search string, pass it to a ColdFusion service that hits the database, and then passes the results to my Handlebars template.

Beautiful - and the code is rather simple. You can test this yourself here: http://www.raymondcamden.com/demos/2012/jul/13/test1.html I'd recommend searching for oil, moon, paint, and beer.

Ok, now let's talk about the next version. The updated version will use LocalStorage to remember your last five searches. I decided on five mostly because it just felt right. I thought ten might be a bit much.

To store the last five values, I'll use an array. You can't store complex variables in LocalStorage, but you can easily serialize them with JSON. So for example:

var pastSearches = [];

if(localStorage["pastSearches"]) {
     pastSearches = JSON.parse(localStorage["pastSearches"]);
}

That isn't too complex, is it? Storing the value isn't too hard either. I do a check to see if the value exists in the array, and if not, put it in the front and pop one off the end if the array is too big.

if(pastSearches.indexOf(search) == -1) {
     pastSearches.unshift(search);
     if(pastSearches.length > 5) {
        pastSearches.pop();
     }
     localStorage["pastSearches"] = JSON.stringify(pastSearches);
}

 All that's left then is to simply write out the past searches and listen for click events on them.

function drawPastSearches() {
    if(pastSearches.length) {
        var html = pastSearchesTemplate({search:pastSearches});
        $("#pastSearches").html(html);
    }
}

$(document).on("click", ".pastSearchLink", function(e) {
    e.preventDefault();
    var search = $(this).text();
    doSearch(search);
});

 And voila - I can now remember your last five searches and provide an easy way for you to quickly rerun them. The code samples above are only the most important bits. I encourage you to View Source on the updated version for the complete example. (The ColdFusion code is just a simple query API. You can view that template here.)

Template Database application Data structure Pass (software) Strings Testing Clear (Unix) JSON

Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How to Submit a Post to DZone
  • The Quest for REST
  • API Design Patterns Review
  • A Brief Overview of the Spring Cloud Framework

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: