栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何扩展EJSON以序列化用于流星客户端

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何扩展EJSON以序列化用于流星客户端

在查看了HowTo和Meteor
EJSON文档之后
,我们可以使用

EJSON.addType
方法序列化RegEx

扩展RegExp- 为RegExp提供

EJSON.addType
实现所需的方法。

RegExp::options = ->  opts = []  opts.push 'g' if @global  opts.push 'i' if @ignoreCase  opts.push 'm' if @multiline  return opts.join('')RegExp::clone = ->  self = @  return new RegExp(self.source, self.options())RegExp::equals = (other) ->  self = @  if other isnt instanceOf RegExp    return false  return EJSON.stringify(self) is EJSON.stringify(other)RegExp::typeName = ->  return "RegExp"RegExp::toJSonValue = ->  self = @  return {    'regex': self.source    'options': self.options()  }

呼叫EJSON.addType- 在任何地方进行。最好使它可用于客户端和服务器。这将反序列化

toJSONValue
上面定义的对象。

EJSON.addType "RegExp", (value) ->  return new RegExp(value['regex'], value['options'])

在控制台中测试 -不要相信我。你自己看。

> o = EJSON.stringify(/^Mooo/ig)"{"$type":"RegExp","$value":{"regex":"^Mooo","options":"ig"}}"> EJSON.parse(o)/^Mooo/gi

这样一来,您就可以在客户端和服务器上对RegExp进行序列化和解析,可以通过有线传递,保存在Session中,甚至可以存储在查询集合中!

编辑以添加IE10 +错误:错误:在严格模式下不允许分配只读属性 由@Tim Fletcher提供

import { EJSON } from 'meteor/ejson';function getOptions(self) {  const opts = [];  if (self.global) opts.push('g');  if (self.ignoreCase) opts.push('i');  if (self.multiline) opts.push('m');  return opts.join('');}RegExp.prototype.clone = function clone() {  return new RegExp(this.source, getOptions(this));};RegExp.prototype.equals = function equals(other) {  if (!(other instanceof RegExp)) return false;  return EJSON.stringify(this) === EJSON.stringify(other);};RegExp.prototype.typeName = function typeName() {  return 'RegExp';};RegExp.prototype.toJSonValue = function toJSonValue() {  return { regex: this.source, options: getOptions(this) };};EJSON.addType('RegExp', value => new RegExp(value.regex, value.options));


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/380426.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号