Search code examples
javascriptjointjs

Event when I assign a cell like source/target on a link?


I use default links and I want to restrict the source and target from links because I want only links between rect(source) and circle(target).

I have tried it with link.on(change:source) and link.on(change:target) but this events don't launch when I want.

Somebody knows some solution for this problem?

    var defaultLinks =  new joint.dia.Link({
            attrs: {
                '.marker-source': {transform: 'scale(0.001)' },
                '.marker-target': {fill:'black', d: 'M 10 0 L 0 5 L 10 10 z' },
                '.connection-wrap': {
                    stroke: 'black'
                }
            },
            smooth:true,
            path: []
    });
    defaultLinks.on('change:source',function(){
        alert("change source")
    });
    defaultLinks.on('change:target',function(){
        alert("change source")
    });

    this.paper = new joint.dia.Paper({
        el: this.paperScroller.el,
        width: 1200,
        height: 1000,
        gridSize: 10,
        perpendicularLinks: true,
        model: this.graph,
        defaultLink: defaultLinks
    });

Solution

  • You can use the validateConnection(cellViewS, magnetS, cellViewT, magnetT, end, linkView) function in the Paper options (http://jointjs.com/api#joint.dia.Paper). This tutorial shows the usage: http://jointjs.com/tutorial/ports#restrict. In your case, you would use something like (not tested):

    var paper = new joint.dia.Paper({
    
        validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
            // Only rectangle can be the source, if it is not, we do not allow such connection:
            if (cellViewS.model.get('type') !== 'basic.Rect') return false;
            // Only circle can be the target, if it is not, we do not allow such a connection:
            if (cellViewT.model.get('type') !== 'basic.Circle') return false;
            // Connection is allowed otherwise.
            return true;
        },
        ...
    })