Is this possible to insert to localstorage or is there other way to store this?
$(\'#pass_to_score\').on(\'click\',function(){
var compressed = function(){
If you have the function encoded in JavaScript, there would be no need to restore it ever from localStorage
, as you already have it available.
You cannot JSON encode a function. You could save the source code of the function, and upon retrieval apply eval
to it. But as all know, this has certain risks, captured in the phrase "eval
is evil".
You could limit that risk a bit, if you would invent an object structure that closely describes what the function should do. In your case, every statement in the function is a method applied to a jQuery selector. This you could represent with the following object:
var compressed = [
{ selector: '.whole_wrap_of_editcriteria', method: 'css', args: ['display', 'none'] },
{ selector: '#wrappler', method: 'css', args: ['display', 'none'] },
{ selector: '#li_addcriteria', method: 'css', args: ['display','none'] },
{ selector: '#li_menu1', method: 'addClass', args: ['active'] },
{ selector: '#home', method: 'removeClass', args: ['active'] },
{ selector: '#menu1', method: 'addClass', args: ['active'] },
{ selector: '#title_panel', method: 'html', args: ['Edit criteria scoring'] }
];
Then your actual function, could take that object as its input, and process it, resulting in the same effect:
var applyInstructions = function(instructions) {
instructions.forEach( cmd => $(cmd.selector)[cmd.method](...cmd.args) );
}
Now, when you want to save this knowledge to localStorage
, you only need to store the above constructed object, like so:
// save to localStorage:
localStorage.setItem('compressed', JSON.stringify(compressed));
And after retrieving it, you would execute the generic function on it:
// get from localStorage:
applyInstructions(JSON.parse(localStorage.getItem('compressed')));
This is similar to using eval
, but it has the advantage that you can put limits to what can be executed (in applyInstructions
). You could for instance check that the method
attribute should only be one of the values css
, addClass
, removeClass
, and html
, although that last one could be a dangerous one to keep. textContent
would be a better alternative, if possible.
Here is how that safer applyInstructions
could look like:
var applyInstructions = function(instructions) {
if (instructions.some(
cmd => ['css','addClass','removeClass','textContent'].indexOf(cmd.method)==-1)) {
throw "Invalid instructions object";
}
instructions.forEach( cmd => $(cmd.selector)[cmd.method](...cmd.args) );
}