Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store a function in IndexedDb datastore

Is it possible in any way to store a function in an IndexedDB datastore? I have done some searching and found nothing on the data types that IndexedDB supports. I tried simply adding a function and the instance of a function to an object store as follows, but it didn't work.

var myclass = function () {
    self = this;
    self.name = 'Sam';
    self.hello = function () {
        console.log('Hello ' + self.name);
    };
}

var transaction = db.transaction(['codeobject'], 'readwrite');
var store = transaction.objectStore('codeobject');
var request = store.put({ 'classname': 'someclass', 'object': myclass });

And I have tried.

var request = store.put({ 'classname': someclass', 'object': new myclass() });

I would really like to be about to store a class in object db. Even if I had to store it as some type of blob and then serialize it back into a function on its way out.

Thank you

like image 894
tribute2ro Avatar asked Feb 14 '23 10:02

tribute2ro


1 Answers

If I get your question right, what you want to do is serialize the entire object including functions?

This is possible to do, you only need to make it possible to serialize functions. For more information about it, see my blogpost about it.

function serialize(key, value) {
    if (typeof value === 'function') {
        return value.toString();
    }
    return value;
}

function deserialize(key, value) {
    if (value && typeof value === "string" && value.substr(0, 8) == "function") {
        var startBody = value.indexOf('{') + 1;
        var endBody = value.lastIndexOf('}');
        var startArgs = value.indexOf('(') + 1;
        var endArgs = value.indexOf(')');

        return new Function(value.substring(startArgs, endArgs), value.substring(startBody, endBody));
    }
    return value;
}

var jsonObj = {
    func: function(){ return ""; }
}
// Turns an object into a json string including functions
var objectstring = JSON.stringify(jsonObj, serialize);

// Turns an object string in JSON into an object including functions.
var object = JSON.parse(objectstring , deserialize);

The objectstring you get can then be saved into the indexeddb.

like image 108
Kristof Degrave Avatar answered Feb 16 '23 03:02

Kristof Degrave