Building a save-state strategy for complex Javascript objects in Max-MSP
When using js or jsui objects, one might end up with a patch whose state is mainly managed by javascript functions and variables. But unlike regular objects, js objects do not have automatically stored parameters that allow to restore their state for further opening.
Declaring attributes
For simple scenarios, there is the declareattribute function that allows to make a variable eligible for persistence. Those attributes are then saved, and even editable in the inspector.
var foo = 2;
declareattribute(“foo”, null, null, 1);The last parameter (1) is required to trigger the embedding of the value on patch save, and the null values indicate the use of the default getter/setter functions. This is fine and works perfectly.
Some more complexity
Imagine that you have a jsui-based interface, allowing the user to create an arbitrary number of objects that have options attached to them. The attributes mechanism does not allow to save complex objects with their properties, so we have to find an alternative solution.
As it is perfectly safe to save an attribute value as a string, I thought of storing all user data in properties of a javascript object, and generating its JSON representation when Max asks for its value. When opening the patch later, the JSON is parsed and datas are then back at their original place.
Basically, my solution looks like this :
var state = {};function setState(s) {
state = JSON.parse(s);
}function getState() {
return JSON.stringify(state);
}declareattribute(“state”, “getState”, “setState”, 1);
This snippet is very straight-forward and does not perform any error checking or validation, so we might spend a little time on the details.
JSON implementation
The first requirement to use this method is to have a JSON implementation to perform the parsing operation. I generated a minified version of Douglas Crockford’s implementation that I pasted at the bottom of my script.
You can parse JSON with a simple eval() command, but it cannot be considered as a secure approach.
Null checking
While editing the patch, there will be situations where your js object will be instantiated with an undefined state, so your JSON parser will fail if you don’t check for that special case.
It is also handy to define a resetState() function that creates a clean state object, so that you avoid the errors caused by missing properties.
Final setup
var state = {};
declareattribute(“state”, “getState”, “setState”, 1);function setState(s) {
if (s) {
state = JSON.parse(s);
} else {
resetState();
}
mgraphics.redraw();
}function getState() {
return JSON.stringify(state);
}function resetState() {
state = {};
}
And voilà.





