2015-04-14 3 views
0

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

 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})) 
}); 

Как это код делает новые элементы удаляются соединения и делает новые, если только кто-то может сказать мне, как удалить элементы и их connecti дополнения с функцией на DblClick я бы очень благодарен ....

ответ

2

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

$(document).on('dblclick','.window',function(){ 
    instance.remove($(this)); 
    //other logic goes here... 
}); 
+0

Это работало так, как я много думал, приятель. – vcuevas

1

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

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

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

+0

Замена #target с .window работает для элементов, которые я уже иметь на data.js, но это не удалять те, которые я создаю с моими кнопками, подскажите почему? Theyre должно быть все оконные классы ... – vcuevas