The forum of the forums

Would you like to react to this message? Create an account in a few clicks or log in to continue.
The forum of the forums
2 posters

    dataStore : localStorage expiration made easy

    Ange Tuteur
    Ange Tuteur
    Forumaster


    Male Posts : 13207
    Reputation : 3000
    Language : English & 日本語
    Location : Pennsylvania

    LocalStorage - dataStore : localStorage expiration made easy Empty dataStore : localStorage expiration made easy

    Post by Ange Tuteur July 10th 2015, 7:59 pm

    Hello,

    This topic is to share a tool for the Web Storage API, and is meant for those with an understanding in JavaScript. Smile


    Introduction

    LocalStorage - dataStore : localStorage expiration made easy Datast10
    Normally when we have to get data we need to make use of AJAX to send a request to another page. Most of the time we want to cache this data so we don't have to send another request. This can sometimes require lengthy conditions, especially with expiration, and of course checking.

    Because of this, I've written a small tool to help make creating expirable Web Storage a whole lot easier.

    Getting Started

    To get started with this tool, you first need to install it on your forum under Modules > JavaScript codes management > Create a new script

    Placement : In all the pages
    Paste the code below and submit
    Code:
    // Methods to make expirable web storage super short and easy
    // Developed by Seth Clydesdale (https://github.com/SethClydesdale/dataStore-JS)
    (function() {
      if (typeof dataStore === 'undefined') {
       
        window.dataStore = {
          on : typeof window.localStorage !== 'undefined',
         
          set : function(name, value, exp) {
            if (dataStore.on) {
              window.localStorage[name] = value;
              if (exp) window.localStorage[name + 'Exp'] = +new Date + '|' + exp;
            }
          },
       
          get : function(name) {
            var o = {
              value : null,
              exp : null
            };
           
            if (dataStore.on) {
              var exp = window.localStorage[name + 'Exp'];
              if (exp) {
                exp = exp.split('|');
                exp = exp.length == 2 ? +exp[0] - (+new Date - +exp[1]) : 0;
              }
             
              o.value = window.localStorage[name] || '';
              o.exp = exp > 0 ? exp : 0;
            }
           
            return o;
          },
         
          del : function(name) {
            if (dataStore.on && window.localStorage[name]) {
              window.localStorage.removeItem(name);
              window.localStorage.removeItem(name + 'Exp');
            }
          }
        };
       
      } else console && console.warn('dataStore is already initialized');
    })();

    You can also follow the installation on Github for a universal installation, or to contribute to this project.
    https://github.com/SethClydesdale/dataStore-JS


    Using dataStore


    Once installed you'll have access to three methods; set, get, and del. See the next sections for information on using these methods.

    LocalStorage - dataStore : localStorage expiration made easy Captur57

    set method


    The set method allows you to save an item to localStorage with (or without) an expiration time. If you're familiar with setItem() then you'll find this similar, only with an extra parameter.

    Syntax : dataStore.set(name, value, exp);

    name : A string which contains the name of your storage item.
    value : The value you want saved to this item.
    exp : A number (in miliseconds) that represents the amount of time the storage item is to be kept. (optional)

    In the example below we set an item name "kitty" to live for 60 seconds.
    Code:
    dataStore.set('kitty', 'meow', 60*1000)


    get method


    The get method allows you to get and return your storage item with its data and expiration time. An object is returned with the following data :

    value : The value that you have saved to localStorage
    exp : The amount of time remaining before the storage item is considered "expired." Every time the object is retrieved, it subtracts the time you submitted against a new date and the creation time.


    Syntax : dataStore.get(name);

    name : A string which contains the name of the storage item you want to get

    In the example below we get the item "kitty." Let's say 30 seconds has passed, so instead of 60000, the exp time will be 30000. ( 30 seconds remaining ) Once the item hits 0 it's considered "expired."
    Code:
    dataStore.get('kitty'); // { value : 'meow', exp : 30000 }

    Here's another example where we access the returned values of "kitty" to check and see if it has a value or if it's expired.
    Code:
    var kitty = dataStore.get('kitty'); // cache returned value

    if (kitty.value && kitty.exp) { // kitty has a value and is not expired
      alert(kitty.value); // alert the stored data
    }
    else {
      dataStore.set('kitty', (kitty.value ? kitty.value : 'meow') + ' meow', 60*1000); // otherwise, add a new meow to storage for 60 seconds
    }


    del method


    The del method allows you to delete both the storage item and expiration date. You can use the native removeItem() method, however this one kills two birds ( value and exp ) in one stone with the aforementioned method.


    Syntax : dataStore.del(name);

    name : A string which contains the name of the storage item you want to delete

    In the example below we delete the value of "kitty" and its expiration date.
    Code:
    dataStore.get('kitty') // { value : 'meow', exp : 60000 }

    dataStore.del('kitty'); // delete the storage item

    dataStore.get('kitty') // { value : '', exp : 0 }


    Usage examples


    Here are some actual examples of using this alongside AJAX to cache the returned data. Note : dataStore must be installed for the examples to function properly.

    You can see the returned data by opening your console. At first it should just be an empty string and a 0, but once the data is set you'll see the difference, especially with the expiration.

    1. Cache and save the user profile

    This example should be applied to an HTML page with using your forum Header and footer. This would also require using the advanced profile layout.

    Code:
    <div id="profileBox"></div>
    <script type="text/javascript">
    (function() {
      var box = document.getElementById('profileBox'),
        data = dataStore.get('profileBox'); // get the storage item
     
      console.log(data); // check your console to see the stored data
     
      if (data.value && data.exp) box.innerHTML = data.value; // check value and expiration time
      else jQuery.get('/u' + _userdata.user_id, function(d) {
        box.innerHTML = $('#profile-advanced-layout', d)[0].innerHTML;
     
      dataStore.set('profileBox', box.innerHTML, 1*60*60*1000); // store HTML for 1 hour
      });
    })();
    </script>


    2. Getting and caching some profile data

    This example should be applied to an HTML page with using your forum Header and footer.

    Code:
    <div id="contacts"></div>
    <script type="text/javascript">
    (function() {
      var box = document.getElementById('contacts'),
          data = dataStore.get('userData'); // get the storage item
     
      console.log(data); // check your console to see the stored data
     
      if (data.value && data.exp) box.innerHTML = data.value; // check value and expiration time
      else jQuery.get('/profile?mode=editprofile', function(d) {
        box.innerHTML = 'Website : ' + jQuery('#profile_field_3_-10', d)[0].value + '<br/>Facebook : ' + jQuery('#profile_field_3_-21', d)[0].value + '<br/>Twitter : ' + jQuery('#profile_field_3_-22', d)[0].value + '<br/>';
     
        dataStore.set('userData', box.innerHTML, 1*60*60*1000); // store HTML for 1 hour
      });
    })();
    </script>
    JScript
    JScript
    Forumember


    Male Posts : 741
    Reputation : 175
    Language : PT-BR, EN
    Location : Brazil

    LocalStorage - dataStore : localStorage expiration made easy Empty Re: dataStore : localStorage expiration made easy

    Post by JScript July 11th 2015, 2:24 am

    @Ange Tuteur
    Excellent! This is the future, goodbye "cookies"...


    I will contribute with an additional information on the topic:

    1. Example of an object to save on storage:
    Code:

    // Object to save in storage...
    var oObject = {
        title: memberTitle.text(),
        state_text: state.html(),
        state_class: state.attr('class')
    };

    2. To save an object in storage:
    Code:

    // Saving object in sessionStorage!
    sessionStorage.setItem(
        'Key_Name',
        JSON.stringify(
            oObject
        )
    );

    3. Getting the object from the storage:
    Code:

    // Readding objsct from storage...
    oObject = JSON.parse(
        sessionStorage.getItem('Key_name');
    );

    This is the basic and can be used with your code!!!

    JS

      Current date/time is November 13th 2024, 7:54 pm