How do I add a class to a JointJS cell?
Asked Answered
Q

2

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...)

Quieten answered 14/8, 2015 at 13:8 Comment(5)
Did you try Vectorizer > addClass(className)?Faery
No. I was under the impression that Vectorizer will work on the DOM objects, which are owned by the view (ElementView), while the above affects the model object (Element).Quieten
Can you provide JSFiddle?Faery
Hmm, the real code is of course part of something relatively large. Rebuilding that will take a while.Quieten
Hmm, you might be right after all, see my answer (about which I am not happy.)Quieten
Q
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.

Quieten answered 15/8, 2015 at 7:14 Comment(1)
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).Mousseline
A
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

Armorer answered 1/8, 2018 at 13:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.