在 Cordova 应用程序中实施 ProtobufJS 时出错

Errors implementing ProtobufJS in Cordova app

我正在编写一个 Cordova 应用程序,目前正在 android 模拟器(x86 图像)上对其进行测试。我正在尝试使用 ProtobufJS 在客户端应用程序和我的服务器之间实现协议缓冲区。我已经使用 javascript 解析器验证所有 JS 文件在语法上都是正确的。有几种方法可以实现 ProtobufJS。我解决的两种方法都会在 android 日志中产生错误。

方法1:使用'pbjs'从proto文件中创建一个JS Class对象。

在我的 index.html 文件中,我有以下脚本标签:

<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/Long.js"></script>
<script type="text/javascript" src="js/ByteBuffer.js"></script>
<script type="text/javascript" src="js/ProtoBuf.js"></script>
<script type="text/javascript" src="js/ClientMessage.js"></script>
<script type="text/javascript" src="js/common.js"></script>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="js/index.js"></script>

在 onDeviceReady 之后的 index.js 文件中,我调用了在 common.js 中定义的 TestProtoObject()。 ClientMessage.js 是生成的 JS class 文件派生自我的 proto 文件。基于 this link 我应该能够通过在协议中定义的包名称引用 class 像这样:

function TestProtoObject()
{
    var blah = new ForeverRPG.ClientMessage();
}

或者通过 _root,我假设是这样的:

function TestProtoObject()
{
    var blah = new _root.ClientMessage();
}

但是,这给了我以下错误:

I/chromium( 2114): [INFO:CONSOLE(169)] "Uncaught ReferenceError: Long is not defined", source: file:///android_asset/www/js/ByteBuffer.js (169)
I/chromium( 2114): [INFO:CONSOLE(1)] "Uncaught TypeError: Cannot read property 'newBuilder' of undefined", source: file:///android_asset/www/js/ClientMessage.js (1)

...

I/chromium( 2114): [INFO:CONSOLE(64)] "Received Event: deviceready", source: file:///android_asset/www/js/index.js (64)
I/chromium( 2114): [INFO:CONSOLE(64)] "Uncaught ReferenceError: ForeverRPG is not defined", source: file:///android_asset/www/js/common.js (64)

"Long" 由 Long.js 定义,但根据 dcodeIO,ByteBuffer 不需要它(ProtobufJS 需要),但是,如果我删除文件,我会在 ByteBuffer.js。我猜最后一个 "not defined" 错误是因为 ClientMessage.js 无法解析。

方法 2:使用 'pbjs' 创建 JSON 我在运行时读入以创建 class: 使用与上面相同的设置,除了没有 ClientMesssage.js 我在 common.js 中添加了一个执行以下操作的方法:

var builder = ProtoBuf.newBuilder();
builder.define("ForeverRPG");
builder.create([
    {
        "package": "ForeverRPG",
        "messages": [
            {
        <JSON here: removed for brevity>
            }
        ]
    }
]);

ForeverRPG = builder.build("ForeverRPG");

但是,这给了我这个错误:

I/chromium( 2357): [INFO:CONSOLE(64)] "Received Event: deviceready", source: file:///android_asset/www/js/index.js (64)
I/chromium( 2357): [INFO:CONSOLE(364)] "Uncaught TypeError: undefined is not a function", source: file:///android_asset/www/js/ProtoBuf.js (364).

我会在评论中提供整个项目 link,因此由于我的新手身份,我的 post 中不会有超过两个 link。

感谢您的帮助,

Dustycoder

@dustycoder 您在 .proto 文件中定义了 package ForeverRPG;,因此,假设您在编译 protobuf 时使用 -t=js,您应该这样写:

var msg = new _root.ForeverRPG.ClientMessage();
/* Theese are wrong:
var blah = new ForeverRPG.ClientMessage();
var blah = new _root.ClientMessage();
*/