Search code examples
javascriptjqueryconnectionjsplumb

JsPlumb: How to create new connection dynamicaly


Here is a problem i've experienced with.

    for (var i=0; i < arr.length; i++) {
        var instance = initializeInstance(wrapperID);
        allConnections.push(instance.connect ( 
            { 
                source  : connectionsArray[j].source, 
                target  : connectionsArray[j].target
            }
        ));
        jsPlumb.fire(".some-selector", instance);
    }

So this is the way i'm saving all the connections on the page between the elements. User has the possibility to add dynamically new elements to the page ... he/she is doing it by dragging the mouse pointer from one element to another on the page ..... i dunno how to add newly created connection into my allConnections array.

   newInstance = initializeInstance(wrapperID);
   newInstance.bind('connection', function(info){
       //   TO DO: push to allConnections Array newly created connection
       //   allConnections.push(this.connect(info.sourceId, info.targetId)); - this line does'n work :(
   });

How to add newly created connection on UI to my allConnections array ?????


Solution

  • Why do you need your own array ?! You can always query jsPlumb to return all connections.

    jsPlumb.getAllConnections() or jsPlumb.select()

    Above will return a connection array. You can use it everywhere instead of using allConnections (array from the code in question)

    Docs - http://jsplumbtoolkit.com/doc/querying

    Secondly, if you still want to add it to your array, then you can bind to events provided by jsPlumb. connection event is fired whenever a new connection is created.

    Docs - http://jsplumbtoolkit.com/doc/events#evt-connection

    Thirdly, there is no need to create multiple instances of jsPlumb. You can simply use jsPlumb.connect or create a single instance of it & use it everywhere. Currently, the code uses jsPlumb, instance and newInstance and the last two being created every now & then.