How to determine the value of the onchange property of an object event?

I have this object:

var Settings = { color: localStorage.color, size : localStorage.size }; 

I would like to automatically save the new values ​​in localStorage after changing them, this means that I would like to do something like this:

 Settings.onchange = function(p){ localStorage[p] = this[p]; }; 

Is it possible?

PS: only Chrome support required.

+4
source share
1 answer

According to a comment by @RobG, I wrote this function and it works!

 function onPropertyChange(o, callback){ for(var p in o){ if(o.hasOwnProperty(p)){ var originalVal = o[p]; Object.defineProperty(o, p, { get: function(){ return originalVal; }, set: function(val){ callback.call(o, p, val); return originalVal = val; } }); } } } // example: var Settings = { color: localStorage.color || "red", size : localStorage.size || "12px" }; onPropertyChange(Settings, function(p, val){ localStorage[p] = val; }); 

gist here: https://gist.github.com/1897209

+2
source

Source: https://habr.com/ru/post/1398160/


All Articles