Удалить узел JsPlumb при dblclick

Я в основном хочу, чтобы 3 кнопки добавляли по 1 другому элементу каждая (уже работает), эти элементы имеют начальную и конечную точки, и когда вы дважды щелкаете элемент, я хочу, чтобы он удалял весь этот элемент и соединения, что делает этот код:

      instance.detachAllConnections("Service1");
      instance.remove("Service1");

но я не могу заставить его работать с событием двойного щелчка... Вот код js, который я получил до сих пор:

    var instanceJsPlumb = null;

    jsPlumb.ready(function () {

    var instance = jsPlumb.getInstance({
        DragOptions: {cursor: 'pointer', zIndex: 2000},

       ConnectionOverlays: [
           ["Arrow", {location: 1}],
       ],
      Container: "sem-dia"
    });

   instanceJsPlumb = instance;

   var basicType = {
         connector: "StateMachine",
       paintStyle: {strokeStyle: "red", lineWidth: 4},
       hoverPaintStyle: {strokeStyle: "blue"},
       overlays: [
        "Arrow"
     ]
  };
   instance.registerConnectionType("basic", basicType);


   var connectorPaintStyle = {
           lineWidth: 4,
           strokeStyle: "grey",
           joinstyle: "round",
           outlineColor: "white",
           outlineWidth: 2
       },

      connectorHoverStyle = {
          lineWidth: 4,
          strokeStyle: "#216477",
          outlineWidth: 2,
          outlineColor: "white"
      },
    endpointHoverStyle = {
        fillStyle: "#216477",
        strokeStyle: "#216477"
    },

    sourceEndpoint = {
        endpoint: "Dot",
        maxConnections: -1,
        paintStyle: {strokeStyle: "#7AB02C", fillStyle: "transparent", radius: 7, lineWidth: 3},
        isSource: true,
        connector: ["Flowchart", {stub: [40, 60], gap: 10, cornerRadius: 5, alwaysRespectStubs: true}],
         connectorStyle: connectorPaintStyle,
         hoverPaintStyle: endpointHoverStyle,
         connectorHoverStyle: connectorHoverStyle,
         dragOptions: {},
         overlays: [

        ]
    },
      targetEndpoint = {
         endpoint: "Dot",
         paintStyle: {fillStyle: "#7AB02C", radius: 11},
          hoverPaintStyle: endpointHoverStyle,
         maxConnections: -1, 
         dropOptions: {hoverClass: "hover", activeClass: "active"},
         isTarget: true,
         overlays: [
         ]
     },
     init = function (connection) {
     };

 var _addEndpoints = function (toId, sourceAnchors, targetAnchors) {

     for (var i = 0; i < sourceAnchors.length; i++) {
         var sourceUUID = toId + sourceAnchors[i];
         instance.addEndpoint(toId, sourceEndpoint, {anchor: sourceAnchors[i], uuid: sourceUUID});
     }
     for (var j = 0; j < targetAnchors.length; j++) {
         var targetUUID = toId + targetAnchors[j];
         instance.addEndpoint(toId, targetEndpoint, {anchor: targetAnchors[j], uuid: targetUUID});
     }
 };

    instance.batch(function () {

      var dia = $("#sem-dia");
      var arr = [];
      $.each(components, function (i, component) {
          if(component.type === 'q'){
              arr.push("<div class='window questions' id='");

          }else{
              if(component.type === 'a'){
                 arr.push("<div class='window answers' id='");
              }else{
                  arr.push("<div class='window other' id='");
              }
          }
          arr.push(component.id);
          arr.push("' style='top: ");
          arr.push(component.y);
          arr.push("px; left: ");
          arr.push(component.x);
          arr.push("px;'> <strong>");
          arr.push(component.name);
          arr.push("</strong><br/><br/> </div>");
      });
      dia.append(arr.join(''));

      $.each(components, function (i, component) {
          _addEndpoints(component.id, ["BottomCenter"], ["TopCenter"]);
      });

      instance.bind("connection", function (connInfo, originalEvent) {
          init(connInfo.connection);
      });

      instance.draggable($("#sem-dia").find("div.window"), {grid: [20, 20]});

      $.each(links, function (i, link) {
          instance.connect({uuids: [link.src + "BottomCenter", link.dst + "TopCenter"],
              editable: true});

      });



      instance.bind("click", function (conn, originalEvent) {
          if (confirm("Delete connection from " + conn.sourceId + " to " + conn.targetId + "?"))
             instance.detach(conn);
              conn.toggleType("basic");
      });

      instance.bind("connectionDrag", function (connection) {
          console.log("connection " + connection.id + " is being dragged. suspendedElement is ", connection.suspendedElement, " of type ", connection.suspendedElementType);
      });

      instance.bind("connectionDragStop", function (connection) {
          console.log("connection " + connection.id + " was dragged");
      });

      instance.bind("connectionMoved", function (params) {
          console.log("connection " + params.connection.id + " was moved");
      }); 

      //This code in a function for any element with a dblclick event that pops an alert and if you press yes it deletes that node and his connections
        //instance.detachAllConnections("Service1");
        //instance.remove("Service1");
  });

       var cont=2;
   $("#botonNewService").mousedown(function(event) {
      var id = "Service" + cont ;
      cont++;
      $("#sem-dia").append("<div class='window other' id='" + id +
      "' style='top: 10em; left: 0em;'><strong>Añadir External Service</strong><br/><br/></div>");
      _addEndpoints(id, ["BottomCenter"], ["TopCenter"]);

      instance.draggable($("#"+id), {containment:true});
      instance.trigger($("#"+id), "mousedown");
      instance.trigger(document, "mousemove");
  });
      var cont2=2;
  $("#botonNewQuestion").mousedown(function(event) {
      var id2 = "Pregunta" + cont2 ;
      cont2++;
      $("#sem-dia").append("<div class='window questions' id='" + id2 +
    "' style='top: 20em; left: 0em;'><strong>Pregunta usuarios</strong><br/><br/></div>");
    _addEndpoints(id2, ["BottomCenter"], ["TopCenter"]);

    instance.draggable($("#"+id2), {containment:true});
    instance.trigger($("#"+id2), "mousedown");
    instance.trigger(document, "mousemove");
});
    var cont3=3;
$("#botonNewAnswer").mousedown(function(event) {
    var id3 = "Respuesta" + cont3;
    cont3++;
    $("#sem-dia").append("<div class='window answers' id='" + id3 +
    "' style='top: 30em; left: 0em;'><strong>Respuesta sistema</strong><br/><br/></div>");
    _addEndpoints(id3, ["BottomCenter"], ["TopCenter"]);

    instance.draggable($("#"+id3), {containment:true});
    instance.trigger($("#"+id3), "mousedown");
    instance.trigger(document, "mousemove");
});


jsPlumb.fire("jsPlumbLoaded", instance);

 });

   $("#botonSave").click(function(){
var components_save = [];
$("#sem-dia").find("div.window").each(function (index) {
    var type = "o";
    if($(this).hasClass("questions")){
        type = "q";
    }else{
        if($(this).hasClass("answers")){
            type = "a";
        }
    }
    var position = $(this).position();
    components_save.push({"id": $(this).attr( "id"), "name": $(this).find("strong").text(), "type": type,
        "x": position.left, "y": position.top})
});

var links_save = [];
if(instanceJsPlumb != null){
    $.each(instanceJsPlumb.getAllConnections(), function (i, connection) {
        links_save.push({"src": connection.sourceId, "dst": connection.targetId})
    });
}

$("#result").text(JSON.stringify({"components":components_save, "links":links_save}))
 });

Поскольку код создает новые элементы, удаляет соединения и создает новые, если бы кто-нибудь мог сказать мне, как удалять элементы и их соединения с помощью функции dblclick, я был бы очень благодарен....


person vcuevas    schedule 14.04.2015    source источник


Ответы (2)


Так как элементы создаются на лету. Вы должны явно добавлять обработчик dblclick каждый раз, когда создается новый элемент. Другим методом (предпочтительнее) было бы присоединить dblclick к document следующим образом:

$(document).on('dblclick','.window',function(){
    instance.remove($(this));
    //other logic goes here...
});
person coding_idiot    schedule 15.04.2015

Вы можете удалить элемент jsPlumb с помощью id="target" двойным щелчком следующим образом:

$("#target").dblclick(function() {
  instance.remove($(this));
});

где instance = jsPlumb.getInstance(...

person alemv    schedule 14.04.2015
comment
Замена #target на .window работает для элементов, которые у меня уже есть в data.js, но не удаляет те, которые я создаю с помощью своих кнопок, есть подсказки, почему? Они должны быть всеми оконными классами... - person vcuevas; 15.04.2015