将函数存储在IndexedDb数据存储区中 [英] Store a function in IndexedDb datastore
问题描述
是否可以以任何方式将函数存储在IndexedDB数据存储区中?我做了一些搜索,没有发现IndexedDB支持的数据类型。我尝试将函数和函数实例添加到对象存储中,如下所示,但它不起作用。
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 });
我试过了。
var request = store.put({ 'classname': someclass', 'object': new myclass() });
我真的想要在对象db中存储一个类。即使我不得不将它存储为某种类型的blob,然后在出路时将其序列化为函数。
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.
谢谢
推荐答案
如果我的问题是正确的,你想要做的是序列化整个对象,包括函数?
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);
然后,您获得的objectstring可以保存到indexeddb中。
The objectstring you get can then be saved into the indexeddb.
这篇关于将函数存储在IndexedDb数据存储区中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!