Skip to content

Instantly share code, notes, and snippets.

@finwo
Created November 15, 2016 14:57
Show Gist options
  • Select an option

  • Save finwo/01903832af7ae77053475dbd92aef337 to your computer and use it in GitHub Desktop.

Select an option

Save finwo/01903832af7ae77053475dbd92aef337 to your computer and use it in GitHub Desktop.
if (typeof define === 'function' && define.amd) {
define('persistent-input', ['jquery', 'localstorage'], function($, localstorage) {
var registeredInputs = {};
var cachedData = {};
/**
* @params {string} key[, {string} value]
* @returns {null}
*/
function data() {
// Simple validation
if (!arguments.length) return null;
// Clone the arguments as they're special
var args = [], key;
for ( key in arguments ) {
if (arguments.hasOwnProperty(key)) args.push(arguments[key]);
}
key = args.shift();
if (args.length) {
var val = args.shift();
localstorage.setItem('persistent-input-'+key, val);
cachedData[key] = val;
}
if (typeof cachedData[key] === 'undefined') {
cachedData[key] = localstorage.getItem('persistent-input-'+key);
}
return cachedData[key];
}
// This will scan the entire document for unknown persistent inputs
function scanNewInputs() {
// Search for persistent inputs
$("[data-persistent]").each(function() {
// Fetch jq object & their name
var $this = $(this),
name = $this.data('persistent') || $this.attr('name') || $this.attr('id');
// Simple validation
if (!name) return;
// Don't register twice
if (registeredInputs[name]) return;
// Set their value from cache
registeredInputs[name] = $this;
var value = data(name);
if ( typeof value !== 'undefined' ) {
$this.val(data(name));
}
$this.on('change', function() {
// Store for later use
data(name, $this.val());
})
});
}
// Let the scanner listen for changes on the entire document
$(document.body).on('DOMSubtreeModified', scanNewInputs);
return data;
});
} else {
console.error("Could not initialize Persistent input without RequireJS");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment