7

I can use the attr method to change attributes of a cell, e.g. to set the stroke of a link:

conn.attr({'.connection': { stroke: 'red' }});

But I would rather set such attributes in the css file, e.g. as in this

.connection {
    stroke: #999;
}

.connection.error {
    stroke: #F00;
}

Is there a way to add such classes to the generated SVG?

I tried

conn.attr({'.connection': { class: 'error' }});

but that removes the .connection class, which is important. It works to write

conn.attr({'.connection': { class: 'connection error' }});

but clearly that will not scale to having multiple orthogonal classes (error, highlighted...)

Joachim Breitner
  • 25,395
  • 6
  • 78
  • 139

2 Answers2

3

In one of the official demos I find this code:

function toggleLive(model, signal) {
    // add 'live' class to the element if there is a positive signal
    V(paper.findViewByModel(model).el).toggleClass('live', signal > 0);
}

I must say that this looks rather like a violation of the model-view separation to me to directly interact with the view this way, but if that is used in the official code then I conclude that this is the most idiomatic way.

Joachim Breitner
  • 25,395
  • 6
  • 78
  • 139
  • Thank you for finding this hidden gem. jQuery can also be used: `$(paper.findViewByModel(model).el).toggleClass('live')`. I know it looks wrong but it's especially useful to associate _data_ or other stuff to it (no `data` function in Vectorizer). If we use use the _$el_ jQuery reference, it becomes even simpler: `paper.findViewByModel(model).$el.data('liveID', 14214)`. – CPHPython Feb 08 '18 at 10:49
1

Anyone looking for answer to this 2015 question in 2018, try this out as well.

I had a similar problem and solved it using highlighters.

cellView.highlight(null, {
    highlighter: {
        name: 'addClass',
        options: {
            className: 'some-custom-class'
        }
    }
});

The above code will add a class some-custom-class to the cell view element. To remove the class, use cellView.unhighlight(...) method with the exact same arguments. Note that now it'll only remove some-custom-class and other classes if present will stay as it is.

Ref: https://resources.jointjs.com/docs/jointjs/v2.1/joint.html#highlighters.addClass

vatz88
  • 2,422
  • 2
  • 14
  • 25