Unable to render JavaScript draw2d canvas using manual extension code

I have implemented additional functionality to my objects within the draw2d canvas. Here is an example:

    var MyConnection= draw2d.Connection.extend({
    init:function(attr){
        this._super(attr);
        this.setRouter(new draw2d.layout.connection.VertexRouter());
        this.setOutlineStroke(1);
        this.setOutlineColor("#000000");
        this.setStroke(3);
        this.setColor('#ffffff');
        this.setRadius(150);
        this.conectionResult={"src":{"nms":true,"trg":true},"trg":{"nms":true,"src":"true"}};
    },


    onContextMenu:function(x,y){
        $.contextMenu({
            selector: 'body',
            events:{
                hide:function(){ $.contextMenu( 'destroy' ); }
            },
            callback: $.proxy(function(key, options){
                switch(key){
                    case "check":
                        result = this.checkConection();
                        this.conectionResult=result;
                        console.log(result);
                        if(result.src.trg && result.trg.src){
                            this.setColor("#FFFFFF");
                        }else{
                            this.setColor("#FF4422");
                        }
                    break;
                    case "report":
                        message=[];
                        result=this.conectionResult;
                        if(result.src.trg && result.trg.src){
                            alert("OK");
                        }else{
                            src=this.getSource();
                            trg=this.getTarget();
                            if(result.src.nms){
                                message.push("NMS Can See "+src.userData.dev_name);
                                if(result.src.trg){
                                    message.push(src.userData.dev_name +" Can See "+trg.userData.dev_name);
                                }else{
                                    message.push(src.userData.dev_name +" CAN NOT See "+trg.userData.dev_name);
                                }
                            }else{
                               message.push("NMS CAN NOT See "+trg.userData.dev_name);
                               if(result.src.trg){
                                   message.push(src.userData.dev_name +" Can See "+trg.userData.dev_name);
                               }else{
                                   message.push(src.userData.dev_name +" CAN NOT See "+trg.userData.dev_name+ " Or NMS Can not confirm it");
                               }
                            }

                            if(result.trg.nms){
                                message.push("NMS Can See "+trg.userData.dev_name);
                                if(result.trg.src){
                                    message.push(trg.userData.dev_name +" Can See "+src.usedData.dev_name);
                                }else{
                                    message.push(trg.userData.dev_name +" CAN NOT See "+src.userData.dev_name);
                                }
                            }else{
                                message.push("NMS CAN NOT See "+trg.dev_name);
                                if(result.src.trg){
                                    message.push(src.userData.dev_name +" Can See "+trg.userData.dev_name);
                                }else{
                                    message.push(src.userData.dev_name +" CAN NOT See "+trg.userData.dev_name+ " Or NMS Can not confirm it.");
                                }
                            }
                            alert(message.join("\n"));
                        }
                    break;
                    case "delete":

                        var cmd = new draw2d.command.CommandDelete(this);
                        this.getCanvas().getCommandStack().execute(cmd);
                    default:
                    break;
                }

            },this),
            x:x,
            y:y,
            items:
            {
                "check":{name:"Check", icon:"edit"},
                "report":{name:"Report",icon:"edit"},
                "sep1":   "---------"
               ,"delete": {name: "Delete", icon: "delete"}
            }
        });
    },
    checkConection:function(){
        src=this.getSource();
        trg=this.getTarget();
        console.log("Source IP:"+src.userData.ip+", Target Ip:"+trg.userData.ip);
        results={"src":{"nms":false,"trg":false},"trg":{"nms":false,"src":false}};
        $.ajax({
            url:"***/index.php?r=/******/check-conection&src="+src.userData.ip+"&trg="+trg.userData.ip,
            async:false,
            success: function(result){
                results=result;
            }
        });
        console.log(results);
        this.conectionResult=results;
        this.setConectionColor();
        return results;
    },
    setConectionColor:function(){
        result=this.conectionResult;
        console.log(result);
        if(result.src.trg && result.trg.src){
            this.setColor("#FFFFFF");
        }else{
            this.setColor("#FF4422");
        }
    }
});

~ I saved these functionalities using an AJAX request to the server.

    function saveTopology(){
    var writer = new draw2d.io.json.Writer();
    writer.marshal(canvas, function(json){
        var jsonTxt = JSON.stringify(json,null,2);                        
        $("pre").text(jsonTxt);
     });
    alert($("pre").text());
    draw2d=JSON.stringify(JSON.parse($("pre").html()));
    var data={
        id      :1,
        draw2d : draw2d,
        map_id : 1
    };
    var url = "topology/save";
    result = AjaxResponce(url,data,"POST");
    $("pre").html(result);
    displayJSON(canvas);

}

I also used the following method to reload the page for subsequent uses.

    function setTopology(){
    write2status("Requesting Topology of map_id 1 ...");
    draw2d.Configuration.factory.createConnection = function (sourcePort, targetPort) {
        var conn = new MyConnection({});
        return conn;
    };
    var topology = AjaxResponce("topology/get-topology",{tplg_id:tplg_id});
    console.log(topology);
    data = topology;
    var bg_map = "url('"+data.bg_map+"')";
    var width = data.width;
    var height = data.height;
    var background_size = height+"px "+width+"px ";
    if(typeof(data.draw2d)==="Array"){
        $.each(data.draw2d,function(index,item){
            if(typeof(item.userData) != "undefined" && Object.keys(item.userData).length >0){
                if(typeof(item.userData.dev_id) !== "undefined")
                    usedDevices.push(item.userData.dev_id);
            }
        });
    }
    topology=JSON.stringify(data.draw2d);
    $(".ui-droppable").css({"background-image":bg_map});
    $(".ui-droppable").css({"height":parseInt(height)*1.1});
    $(".ui-droppable").css({"width":parseInt(width)*1.1});
    write2status("Adding map to page...");
    $("pre#json").html(topology);
    write2status("Map added...");
}

I have set

draw2d.Configuration.factory.createConnection = function (sourcePort, targetPort) {
    var conn = new MyConnection({});
    return conn;
};`

The functionalities work fine when I open a new form, but the added functionalities do not load after reloading the page even though they are assigned to any new objects added to the page after the reload. Can someone help me solve this issue?

Answer №1

After successfully resolving the issue, I have some uncertainty regarding the correctness of my approach. I made a simple modification:

 var MyConnection= draw2d.Connection.extend({

in the initial code to

 draw2d.Connection = draw2d.Connection.extend({

I then proceeded to eliminate the relevant portions of a third file. Consequently, Draw2d now loads My connection instead of the default function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for a particular product edit page showing up completely blank?

In my ongoing project, I am developing an admin panel that allows administrators to add new products to their website. These products are then stored in a Firestore database and managed using Redux Toolkit. The added products can be viewed and edited in th ...

Exploring the data connections in Firebase Realtime Database using angularfire2

I am in need of querying comments and only requesting users that are listed in the comment by their userId. This is the structure of my database in Firebase realtime db: { "comments" : { "c_id1" : { "commentId" : "c_id1", "commentText" ...

How to trigger an Angular (ionic) view update following an HTTP post request

Is there a way to update the expression in my view after making an HTTP post request? I have tried using the $scope.$apply function, but it gives me an error from ionic.bundle.js saying "$digest already in progress". Could this be a mistake on my part or ...

[Vue alert]: Issue with rendering: "TypeError: Unable to access property 'replace' of an undefined value"

I'm currently working on a project similar to HackerNews and encountering the following issue: vue.esm.js?efeb:591 [Vue warn]: Error in render: "TypeError: Cannot read property 'replace' of undefined" found in ---> <Item ...

Unable to retrieve all the necessary data from the LinkedIn API

I have attempted the following: Code Snippet in HTML: <a id="li_ui_li_gen_1432549871566_0-link" class="" href="javascript:void(0);" onclick="onLinkedInLoad();" style="margin-bottom: 20px;"> Javascript Function: function onLinkedInLoad(logintype) ...

Having trouble with the JsonLoader copied from Threejs.org?

I've been trying to make use of a JSONLoader from threejs.org, but I'm facing some issues. Three.js seems to be functioning properly because I can easily create a cube. However, when I attempt to load a js file through the JSONLoader, nothing hap ...

Internet Explorer has been known to remove option tags that are added dynamically through

I've come across a code snippet that works perfectly in all browsers except IE. Here it is: var array = eval( '(' + xmlHttp.responseText + ')' ); var html = ''; for(var key in array) { html += '<option value ...

Is there a way for me to make my Note element automatically update whenever I modify its text content?

Feeling a bit stuck with my project, especially this part. I'm currently using React to develop a notes application, and I'm having trouble updating the note when changing the text within the modal popup. The commented sections are where I need h ...

Icon not displaying in Firebase background service worker notifications with JavaScript

Although my firebase-messaging-sw.js is functioning properly in displaying background notifications, I have encountered an issue where the icon does not show up even though notification.title and notification.click_action are working correctly. Here is th ...

Tribal Code Typescript Compiler

Typescript is a great alternative to Javascript in my opinion, but it bothers me that it requires node.js as a dependency. Additionally, I find it frustrating that there seems to be only one compiler available for this language, and it's self-hosted. ...

The OnKeyDown function may encounter issues in IE9, whereas it functions properly in all other browsers

I am facing an issue with the onkeydown property in a JavaScript function that triggers an alert. While it works perfectly fine in Chrome and Firefox, it seems to be failing in Internet Explorer 9. The keydown, keyup, and keypressed events do not seem to w ...

The D3js visualization is failing to display properly for the user, with the D3 source code residing on the server

I have encountered an issue after transferring my D3js chart generation system from a development server with no problems to a live Windows 2008 r2 server. On the live server, only the background SVG element is displayed and none of the other elements like ...

Encountered a problem with AngularUniversal prerendering: UnhandledPromiseRejectionWarning: Unable to locate NgModule metadata for 'class{}'

Objective The task may seem lengthy, but it's straightforward! Currently, I am utilizing Angular Universal for Server-Side Rendering (SSR) by following a tutorial. The Universal/express-engine has been installed, main.js is generated in the dist/pro ...

What is the best way to utilize an audioStream provided by the Amazon Lex SDK during the process of recognizing a spoken phrase?

I have successfully built a chatbot using Amazon Lex and integrated it with a Node.js Rest API by following the official documentation. After sending a RecognizeUtteranceCommand, I am receiving an audioStream in the response. Now, the main challenge I&ap ...

What causes parameters to be initially passed as undefined when sending them from one component to another, only to later arrive with the actual data intact

When passing properties from a parent component to a child component, my code gets executed before the properties arrive. This results in an error stating "Cannot read properties of undefined (reading 'map')". Why does this occur? https://i.ssta ...

Guide on programmatically choosing an option within a variable with the help of jQuery

Imagine having a variable named html, which holds select options like this: var html = '<select>'+ '<option value="10">10</option>'+ '<option value="20">20</option>'+ ...

Information regarding gender vanishes upon refreshing the page

When the page is refreshed, the variable called jso disappears. Is there an alternative method for storing information that does not involve using a button? The goal is to have it work seamlessly when the page is reloaded without requiring any user action. ...

Are there any tools available that can convert ThreeJS code into WebGL?

Are there any existing tools that can convert ThreeJS to WebGL? Or, could you provide guidance on creating a converter for ThreeJS to WebGL? ...

What is the best way to extract and retrieve the most recent data from an XmlHttpRequest?

Currently, I am using a web service that returns an SseEmitter to program a loading bar. The method to receive it looks like this: static async synchronize(component: Vue) { let xhr = new XMLHttpRequest(); xhr.open('PATCH', 'myUrl.co ...

Middleware in the form of Try and Catch can be utilized to handle errors and

Currently, I am working on developing a backend using node.js with Express. My main goal is to effectively handle any potential status 500 errors that may arise. router.put('/test', async (req, res) => { try { return res.send(await r ...