使用自定义属性扩展到对象的结构js将丢失默认属性

时间:2016-12-22 15:28:11

标签: javascript json fabricjs

Befor发布这个我一直在这里和其他许多地方一样,但我可以完全开始工作。

我只需要能够在所有形状中保存一些自定义属性。属性是:uuid和rt_attributes。

因此,正如手册我添加了这段代码:

 fabric.Object.prototype.toObject = (function(toObject) {
  console.log(toObject)
  return function() {
    return fabric.util.object.extend(toObject.call(this), {
      uuid: this.uuid,
      rt_attributes: this.rt_attributes
    });
  };
})(fabric.Object.prototype.toObject);

在某种程度上可以正常工作。

当我在json中序列化并加载时问题就出现了。 自定义属性所在,但像IText这样的形状会引发异常,例如:

fabric.js:22199 Uncaught TypeError: Cannot read property 'split' of undefined

查看转储的json我可以看到.text属性未导出。所以我担心覆盖toObject会失去默认对象的一些自定义属性。

当然我可以在我的toObject函数中使用所有缺少的修剪重新定义它,但我尽管如此

fabric.util.object.extend

会为我做的。

有人能指出我做错了什么吗? 谢谢。 升。

P.S 这是结果json的片段:

{"type":"i-    text","originX":"left","originY":"top","left":29,"top":677,"width":107,"height":22.6,"fill":"rgba(255,255,255,1)","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"uuid":"04af6ab4-4eb1-432b-f46a-93b11a92292d","rt_attributes":[["fontFamily","text"],["fontSize","int"],["fill","color"],["opacity","float"],["top","int"],["left","int"]],"styles":{}},

你可以看到没有文字字段。但是uuid和rt_attributes都在。

1 个答案:

答案 0 :(得分:4)

终于找到了正确的方法:

fabric.Object.prototype.toObject = (function (toObject) {
    return function (propertiesToInclude) {
        propertiesToInclude = (propertiesToInclude || []).concat(
          ['uuid','rt_attributes']
        );
        return toObject.apply(this, [propertiesToInclude]);
    };
})(fabric.Object.prototype.toObject);
相关问题