Question

I have an existing client side application that makes use of javascript objects that look something like this:

var myObject = {
   Id: 1,
   Name: 'Foo',
   Property1: 123,
   Property2: 'ABC',
   MyMethod: function() { ///do something },
   MyMethod2: function() { /// do something else }
};

I am now looking to try to persist these objects using a service such as Firebase. Firebase doesn't like the properties that contain the functions, so I want to know if there is a 'simple' way of stripping out the offending functions when saving to Firebase and then reattaching them on retrieval without having to create copies of each of the objects.

Was it helpful?

Solution

A fairly common pattern is to have a constructor function with the relevant functions attached to it, and to have that constructor accept a raw version of the object that it uses to populate itself as well as a "toRaw" or similar function that gives you the raw copy.

For example:

function Thingy(raw) {
    var name;
    for (name in raw) {
        if (raw.hasOwnProperty(name)) {
            this[name] = raw[name];
        }
    }
}
Thingy.prototype.MyMethod = function() { /* ... */ };
Thingy.prototype.MyMethod2 = function() { /* ... */ };
Thingy.prototype.toRaw = function() {
    var raw, name, value;
    for (name in this) {
        if (this.hasOwnProperty(name)) {
            value = this[name];
            if (typeof value !== "function") {
                if (value.toRaw) {
                    raw[name] = value.toRaw();
                } else {
                    raw[name] = this[name];
                }
            }
        }
    }
};

Then when saving to Firebase:

write(myObject.toRaw());

...and when reading from Firebase:

var obj = new Thingy(read());

More complicated handling would involve putting a memo on the raw object to tell you whether one of the object's properties is, itself, using this pattern, so you know to call the constructor for it rather than just copying it. (The eagle-eyed will note that the example above is assymetrical, it allows for toRaw on properties when serializing in toRaw, but doesn't when deserializing in Thingy.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top