我能否在JointJS元素中添加新属性?

12

我想创建一个具有新属性的自定义元素,我已经创建了我的自定义元素,但我需要一个新的属性来存储有关该元素的信息。

joint.shapes.basic.newRect = joint.shapes.basic.Generic.extend({

markup: '<g class="rotatable"><g class="scalable"><rect/></g><text/></g>',

defaults: joint.util.deepSupplement({

    type: 'basic.newRect',
    attrs: {
        'rect': { fill: 'white', stroke: 'black', 'follow-scale': true, width: 80, height: 40 },
        'text': { 'font-size': 14, 'ref-x': .5, 'ref-y': .5, ref: 'rect', 'y-alignment': 'middle', 'x-alignment': 'middle' }
    }

}, joint.shapes.basic.Generic.prototype.defaults)

谢谢!


你能提供更多关于你想要存储的额外信息的信息吗? - Ryan G
一个字符串向量 ['1','2','3'....] - csadan
2个回答

13

你可以在typeattrs旁边添加新的属性。这些将成为您元素的默认属性,如下所示:

joint.shapes.basic.newRect = joint.shapes.basic.Generic.extend({

markup: '<g class="rotatable"><g class="scalable"><rect/></g><text/></g>',

defaults: joint.util.deepSupplement({

    type: 'basic.newRect',
    attrs: {
        'rect': { fill: 'white', stroke: 'black', 'follow-scale': true, width: 80, height: 40 },
        'text': { 'font-size': 14, 'ref-x': .5, 'ref-y': .5, ref: 'rect', 'y-alignment': 'middle', 'x-alignment': 'middle' }
    },
    mycustom: 'foo'

}, joint.shapes.basic.Generic.prototype.defaults)

稍后当您实例化元素时,您还可以仅将属性添加到该特定元素:

var myNewRect = new joint.shapes.basic.newRect({ position: { x: 1, y: 1 }});
myNewRect.set('mycustom2', 'bar')
myNewRect.get('mycustom') // 'foo'
myNewRect.get('mycustom2') // 'bar'

在序列化图形时,所有这些属性也将被考虑在内。


@dave 在这个例子中,我应该选择哪个更好:myNewRect.set('mycustom', 'foo') 还是 myNewRect.prop('mycustom', 'foo')?而且由于没有 removeProp() 方法,我该如何移除这个元素呢? - user3142695
@user3142695,set()和prop()都适用于平铺属性。prop()的威力在于嵌套属性。例如:el.prop('mycustom/nested/object/property', 'foo')。关于removeProp(),你说得对!它确实存在,但我们的API文档中不知道为什么把它给跳过了。如果你下载http://jointjs.com/downloads/joint.js并搜索"removeProp",你就能找到它。它的签名很简单:removeProp(path[, opt])。 - dave

2

prop()set()有什么区别? - user3142695
Prop 是针对自定义数据属性的。 - Diogo Garcia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接