Building a simple plugin using jQuery (Should know)

Up until now, we've worked with Local Storage directly in our code. While this will work perfectly well, it's not an ideal solution; it improves messy code if it is held inline, and adds a lot of unnecessary code to a site. A better option is to separate the code and turn it into a plugin that we can re-use; we will see how we can build a simple plugin as part of this recipe.

Getting ready

For this recipe, all you will need is your text editor. Anything else that is required is called directly from within the code.

How to do it...

Perform the following steps, to build a simple plugin using jQuery:

  1. Let's begin with adding the following code snippet to a new HTML document, and save it as basicplugin.html:
    <!DOCTYPE html>
    <head>
      <title>Basic plugin test</title>
      <meta charset="utf-8">
      <script src=
      "http://code.jquery.com/jquery-1.8.3.min.js"></script>
      <script src="jquery.alStorage.js"></script>
    </head>
    <body>
      <div id="demoresults">
        <div id="details">
          <h2>Demo using alStorage</h2>
          <p></p>
        </div>
      </div>
    </body>
    </html>
  2. We need to provide the script that will save some content to LocalStorage, and then retrieve it, so add the following code in between the <p> tags:
      <script type "text/javascript">
        var testItem = "Hello, my name is Alex.";
        $.alStorage.setItem("testObject", testItem);
        document.write("The value in the 'testObject' key has 
        been saved to LocalStorage.<p>")
        var retrievedObject = 
        $.alStorage.getItem("testObject");
        document.write("The retrieved value is: " + 
        retrievedObject);
      </script>
  3. We still need to perform a couple of steps for getting a working example. As it stands, it won't win any awards for styles, so let's add some basic styles to at least make it look presentable! Add the following code into the <header> area of our document. We've included a Google web font for good measure:
    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Berkshire+Swash" >
    <style type="text/css">
      body { color: #FFF; }
      h2 { padding: 5px; margin-top: -5px; 
      font-family: 'Berkshire Swash', cursive; }		
      p { padding: 5px; font-family: tahoma, 
      arial, sans-serif; }	
      #demoresults { border: 1px solid black; border-radius: 
      6px; height: 240px; padding: 0 10px 5px; width: 375px; }
      #details { background-color: #369; height: 89.5%; 
      margin-top: 10px; padding: 5px; }
    </style>
  4. Here's where the meat and bones of this demo lie. Add the following code to a new text document, and save it as jquery.alstorage.js; this provides the iQuery functions that are called from the main code:
    (function($){
      $.alStorage = {
        setItem: 
        function(key,value){localStorage.setItem(key,value)},
        getItem: 
        function(key){return localStorage.getItem(key)},
        removeItem: 
        function(key){localStorage.removeItem(key)},
        clearItem: function(key) {localStorage.clear()}
      }
    })(jQuery);
  5. If all is well, you should see something similar to the following screenshot when previewing this in your browser:
    How to do it...

How it works...

In this recipe, we've taken the normal methods available for Local Storage and moved them into a jQuery plugin. We've encased each method call into a method handler, so that from within our code, we can call the appropriate method in the same way, as if the methods had been within the main code and not in a separate plugin file. To demonstrate it, we've used the setItem method for the phrase Hello, my name is Alex with a testObject key in Local Storage. We've then retrieved the text from the same value using the getItem method.

There's more...

This little plugin serves as a perfect illustration of how you can encase Local Storage into a jQuery plugin. You're probably thinking, "Great, I can use this in my code; I'm good to go now." Except probably not.

Huh? It might seem odd to say that, but there is a good reason—there are some points to consider here:

  • Although this plugin works, it does not follow the best practice. It was meant to illustrate how you could encapsulate Local Storage within a jQuery plugin. You would very likely want to redesign it to follow accepted best practice. For a good starting point, you may want to take a look at JQuery 1.4 Plugin Development Beginner's Guide by Giulio Bai, Packt Publishing.
  • There is no scope within this plugin to cover Session Storage as it stands. You can easily rewrite this plugin to include support for Session Storage too. This is important, as you will need to store content in the browser that would only need to be there for the current session—using Local Storage isn't appropriate in this instance.
  • A benefit of using a plugin is that you can provide consistent support for Local Storage, while abstracting the code required for using it natively, or falling back to a polyfill for older browsers. The important thing to bear in mind here is, do you need to provide fallback support? This all depends on the browsers that your visitors are using to view your site. If they are all using modern browsers, there is little need for providing an extra layer of code, when the native equivalent will suffice. If you do still have older browsers being used (which is more likely), a plugin will serve you well.
  • Although you can write your own plugin, it may be more sensible to look and see what is available for use already; several people have created plugins and made them available for download. It may be a better use of your development time to see what is available and whether it suits your needs or not, before going ahead with developing your own plugin.

That last consideration raises an important point. It may be a better use of your time to complete some research with a view to potentially using a plugin that someone has already made available for use, and which already contains additional functionality that you are looking to use in your project. A good example of this could be to provide TTL support for Local Storage, as well as support for storing arrays in Local Storage; as it so happens, there is a plugin that does both of these and more. In the next recipe, we're going to take a look at jStorage, and why you are not always forced to use strings when storing content!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset