amplify custom cache

by spring1975

HTML

<script src="https://raw.github.com/appendto/amplify/master/core/amplify.core.js"></script>
<script src="https://raw.github.com/appendto/amplify/master/request/amplify.request.js"></script>
<script src="https://raw.github.com/appendto/amplify/master/store/amplify.store.js"></script>
  <p id="hello">Hello World</p>
  <input class="cacheCondition" type="checkbox" checked="checked" />

JavaScript

// i've created this condition to use for determining if the cache should be used or not. this could be any outside condition, or you could write the check in the cache code itself.
var stayCached = true;

amplify.request.cache.persistSometimes =
  function( resource, settings, ajx, ampXHR ) {
      
    // create own custom key.
    // see https://github.com/appendto/amplify/blob/master/request/amplify.request.js#L215
    var cacheKey = amplify.request.cache._key( settings.resourceId,
                                               ajx.url, ajx.data );
        
        // get cached data
        cached = amplify.store( cacheKey );
      
        // if cached AND our extra condition
        if( cached && stayCached ) {
      
          console.log( "cached!!!" );
      
          ajx.success( cached );
          return false;
        }
    
    // hijack success callback
    var success = ampXHR.success;
    ampXHR.success = function( data ) {
      
      console.log( "not cached, adding now" );
      
      amplify.store( cacheKey, data);
      
      // perhaps reset your condition here. it depends
      // on what you are looking for
      stayCached = true;
      
      // call our original callback
      success.apply( this, arguments );
    };
  };

amplify.request.define( "someData", "ajax", {
  url: "/echo/html/",
  type: "POST",
  dataType: "html",
  data: { html : "<p>Text echoed back to request</p>" },
  cache: "persistSometimes"
});

setInterval( function() {
    amplify.request( "someData", function( data ) {
        console.log( data );
    } );
}, 3000 );


$( ".cacheCondition" ).bind( "click", function() {
  stayCached = $(this).is( ":checked" );
});