So, I’ve got a javascript object, to which I’ve attached several methods via prototype.
No worries there.
Now, when I persist that object to JSON, only the actual property values are persisted. That makes perfect sense. How would you persist methods, anyway, right?
But, when I depersist the JSON object, I end up, of course, with an object that looks, property-wise, like my original object, which which no longer has any methods associated with it at all.
I understand +why+ that happens.
My question is, is there already a pattern of some sort for handling this situation?
For my own part, I have turned up a small js library called Classy classes for JS, which allows you to do something like this.
var MyClass = Class.$extend({
__init__ : function() { alert('called'); },
toString() : function() {
return this.value;
})
});
var obj = MyClass.$withData({value: 42});
alert(obj.toString());
This +does+ work, but I can’t see a way to easily apply it to a deep hierarchy of objects.
EDIT: I wasn’t very clear initially. I know that Classy (and jquery proper, as I’ve just been made aware) can apply data to a specific object to blend in prototyped methods, but the real question is how to do that for a deeper hierarchy of objects.
If you have e.g. jQuery you can use
$.extend(obj, yourDataFromJSON);This will merge all data from the second object into the first one, overwriting existing values.
However, according to the Classy code you can actually simply use
MyClass.$withData(yourDataFromJSON);even for nested data:As you can see, everything from
datais put into the object – no matter if it’s another object (if you have nested data), an array or anything else that is notundefined(which doesn’t even exist in JSON)