JointJS: Require target element when creating link
I'm trying to avoid links ending in space and I only want to allow links connecting one element to another. My current code:
new joint.shapes.basic.Rect({
id: id,
size: {
width: width,
height: height
},
attrs: {
text: {
text: label,
'font-size': letterSize
},
rect: {
width: width,
height: height,
rx: 5,
ry: 5,
stroke: '#555',
'magnet': true
}
}
});
And for the article:
var paper = new joint.dia.Paper({
el: $('#paper-basic'),
width: 1250,
height: 1000,
model: graph,
gridSize: 1,
validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
// Prevent linking from output ports to input ports within one element.
if (cellViewS === cellViewT) return false;
// Prevent linking to input ports.
return magnetT;
},
markAvailable: true
});
How can I require each link to have a source and a purpose? Expanding perhaps validateConnection
?
source to share
If this is still relevant, there is now an linkPinning
on option Paper
:
http://jointjs.com/api#joint.dia.Paper:options
linkPinning - If set to true (default), links can be anchored to a document, meaning the source or target of the link can be a dot. if you don't want the user to drag the link and drop it somewhere in the blank area of the paper, set this to false. The effect is that the link will return to its original position whenever the user drops it somewhere in an empty paper area.
source to share
Confirmation of the connection will only help with checking the magnets, it is not called when the end of the link is in a random space on paper. You can remove incomplete links with the following:
// keep links from being incomplete
function isLinkInvalid(link){
return (!link.prop('source/id') || !link.prop('target/id'));
}
paper.on('cell:pointerup', function(cellView) {
if (! (cellView.model instanceof joint.dia.Link) ) return; // if it not a link, don't worry about it
// otherwise, add an event listener to it.
cellView.model.on('batch:stop', function(){
var links = graph.getLinks();
links.forEach(function(link){
if(isLinkInvalid(link)){
link.remove();
}});
});
});
It adds an eventListener to the link. This is important to do on 'cell:pointerup'
, because when the link is created, it is called 'batch:stop'
. If the link does not have a target ID, then it is not connected to the port.
source to share
slightly different / shorter answer combining @Anora s and https://groups.google.com/forum/#!topic/jointjs/vwGWDFWVDJI
paper.on('cell:pointerup', function (cellView, evt) {
var elem = cellView.model
var source = elem.get('source')
var target = elem.get('target')
if (elem instanceof joint.dia.Link && (!source.id || !target.id)) {
elem.remove()
}
})
source to share