我正在使用自定义类型构建Drive Realtime项目:https://developers.google.com/google-apps/realtime/custom-objects。
我遇到的问题是我的自定义对象中的字段未在model.toJson()输出中导出。我确定我只是遗漏了一些东西,但我还没有找到与构建自定义对象与实时游乐场或实时API文档的方式有任何区别。
使用实时游乐场的示例repro案例如下。
1)去实时游乐场:https://realtimeplayground.appspot.com/ 2)打开开发者控制台 3)运行以下代码
test = function () {}
test.prototype = { init: function() { this.name = 'testName';}};
test.prototype.name = gapi.drive.realtime.custom.collaborativeField('name');
gapi.drive.realtime.custom.registerType(test, 'testType')
gapi.drive.realtime.custom.setInitializer(test, test.prototype.init);
var model = window.doc.getModel()
model.getRoot().set('myTest', model.create(test));
model.toJson()
观察输出:
"{"id":"root","type":"Map","value":
{"demo_string":
{"id":"Tq50c9iybcXi","type":"EditableString","value":"Edit Me!"},
"demo_list":{"id":"ZmjclOeUbcXj","type":"List","value":
[{"json":"Cat"},{"json":"Dog"},{"json":"Sheep"},{"json":"Chicken"}]},
"demo_cursors":{"id":"6TJ6Zzd2bcXj","type":"Map","value":{}},
"demo_map":{"id":"ukRRMPHbbcXj","type":"Map","value":
{"key1":{"json":"value 1"},"key2":{"json":"value 2"},"key3":{"json":"value 3"}}},
"demo_custom":{"id":"44nsuMAPbcXk","type":"DemoMovie","value":
{"name":{"json":"Minority Report"},
"director":{"json":"Steven Spielberg"},
"notes":{"json":""},"rating":{"json":""}}},
"myTest":{"id":"Kq4hcV4UbcvW","type":"testType","value":{}}}}"
预期:
"{"id":"root","type":"Map","value":
{"demo_string":
{"id":"Tq50c9iybcXi","type":"EditableString","value":"Edit Me!"},
"demo_list":{"id":"ZmjclOeUbcXj","type":"List","value":
[{"json":"Cat"},{"json":"Dog"},{"json":"Sheep"},{"json":"Chicken"}]},
"demo_cursors":{"id":"6TJ6Zzd2bcXj","type":"Map","value":{}},
"demo_map":{"id":"ukRRMPHbbcXj","type":"Map","value":
{"key1":{"json":"value 1"},"key2":{"json":"value 2"},"key3":{"json":"value 3"}}},
"demo_custom":{"id":"44nsuMAPbcXk","type":"DemoMovie","value":
{"name":{"json":"Minority Report"},
"director":{"json":"Steven Spielberg"},
"notes":{"json":""},"rating":{"json":""}}},
"myTest":{"id":"Kq4hcV4UbcvW","type":"testType","value":{"json":"testName"}}}}}"
答案 0 :(得分:0)
注册自定义类型只能在" Pre-Load"文档生命周期的阶段。您的代码是正确的,但正在>>文档加载后的文档上执行。这会导致自定义对象无法正确构造,这就是为什么它缺少您在init函数中指定的JSON值。
要查看正确的流程,请在Realtime Playground应用程序中的static / elements / playground-app.js的第88行放置一个断点。刷新页面,当执行暂停时,从控制台运行此代码:
test = function () {}
test.prototype = { init: function() { this.name = 'testName';}};
test.prototype.name = gapi.drive.realtime.custom.collaborativeField('name');
gapi.drive.realtime.custom.registerType(test, 'testType')
gapi.drive.realtime.custom.setInitializer(test, test.prototype.init);
恢复执行。当应用程序完全加载后,运行其余代码:
var model = window.doc.getModel()
model.getRoot().set('myTest', model.create(test));
model.toJson()
您将看到输出的JSON符合您的预期:
"myTest":{"id":"1OiQd2QoEqBs","type":"testType","value":{"name":{"json":"testName"}}}
此工作流程记录在"注册自定义类型和字段" Custom Collaborative Objects指南的标题。