Home > Web Front-end > JS Tutorial > body text

How to let JS automatically match proto Js

php中世界最好的语言
Release: 2018-03-16 10:49:12
Original
1679 people have browsed it

这次给大家带来让JS自动匹配出proto Js的方法,JS自动匹配出proto Js的方法的注意事项有哪些,下面就是实战案例,一起来看一下。

在与后端的WebSocket通信时,前端要带一个proto文件是一个累赘的事情。首先是明显的曝光了协议实体对象,再一个浏览器客户端很容易会缓存该文件,新的协议更新可能导致客户端不能使用,另外在cdn服务器上还需要配置.proto类型客户端才能下载过去。真是遗毒不浅,自己使用的时候会注意这些,但给别人使用的时候就很不乐观了,所以这次全部将proto文件转成JavaScript对象,省去协议文件和加载的步骤。

先看代码:

  args = [].slice.call(arguments, 1 obj =  ( i = 0; i < args.length; i++ p = key = i + 1 protobuf.Field(p[0], key, p[1] || "string" obj =  ( i = 0; i < list.length; i++ ( protobuf == "undefined") ;=  protobuf.Root().define("IMEntity""Token", ["UserID"], ["Token"], ["Device"], ["Version", "int32"], ["Appkey""Feedback", ["ResultCode", "int32"], ["ResultData"], ["Seq", "int32"], ["MsgID""ReceiptType", ["Receive", "Read"
    };
Copy after login

proto 主要有两种类型,Type和Enum。Type对应协议中的message,相当于是类。Enum就是枚举类型

var Root  = protobuf.Root,
    Type  = protobuf.Type,
    Field = protobuf.Field;var AwesomeMessage = new Type("AwesomeMessage").add(new Field("awesomeField", 1, "string"));var root = new Root().define("awesomepackage").add(AwesomeMessage);
Copy after login

枚举的创建不要需要Field。只需要add 字段名即可。那么接下来的问题是,手写root.add 也很烦,因为要一个一个对照属性,不断的复制粘贴,很容易出错。所以又做了个自动生成代码的页面:

 
    

    
Copy after login

然后页面上会得到:

红色部分复制到工程里面就可以用了。当然要带上createProto和createEnum两个方法。proto的格式要规范,毕竟start里面是以空格split的。相对于protobuf.load("xx.proto",callback)的方式要好很多。load对位置要求比较死板,一定要在根目录。而且有类型不存在就会报错,终止程序。add方法不存在找不到类型的错误。另外速度也快了很多。 

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样让js暂停执行

jquery做出评分系统

The above is the detailed content of How to let JS automatically match proto Js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!