Store a function in IndexedDb datastore

泄露秘密 提交于 2019-12-06 06:08:47

问题


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


回答1:


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.




回答2:


You can store the function as a string:

store.put({ 'classname': 'someclass', 'object': myclass.toString() });

And then deserialize it back into a function via eval:

var myclass = Function('"use strict";return ' + functionString);


来源:https://stackoverflow.com/questions/22545031/store-a-function-in-indexeddb-datastore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!