Is it possible to refresh a tree without having to reload the entire webpage?

I'm currently developing a web application utilizing zTree library. The tree structure is populated with data retrieved from a Golang backend server. Each leaf node in the tree should have custom icons that can change dynamically while the application is running. How can I achieve this icon customization based on backend data without having to refresh the entire page?

Using http-equiv="refresh" for automatic page refresh causes annoying blinking and loss of focus. Below is a working example with zTree where the page does refresh, but it blinks (I omitted the backend-related part for simplicity):

<HTML>
<HEAD>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta http-equiv="refresh" content="5">
    <link rel="stylesheet" href="../static/css/zTreeStyle/zTreeStyle.css" type="text/css">
    <script type="text/javascript" src="../static/js/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="../static/js/jquery.ztree.core.js"></script>
</HEAD>

<BODY>
    <div id="app">
        <TABLE>
            <TR>
                <TD width=260px valign=top>
                    <ul id="tree" class="ztree"></ul>
                </TD>
                <TD valign=top>
                    <p>Some text</p>
                </TD>
            </TR>
        </TABLE>
        
        <SCRIPT type="text/javascript">
            var zTree;
            var setting = {
                data: {
                    simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "pId",
                    rootPId: ""
                    }
                }
            };
            var zNodes = [
                {id: 1, pId: 0, name: "root", icon:"../static/css/zTreeStyle/img/diy/c16green.png"},
                {id: 2, pId: 1, name: "leaf", icon:"../static/css/zTreeStyle/img/diy/c16red.png"},
            ];
            $(document).ready(function () {
                var t = $("#tree");
                t = $.fn.zTree.init(t, setting, zNodes);
            });
        </script>
    </div>
</BODY>
</HTML>

I attempted to incorporate Vue.js for data binding to zTree nodes, but encountered difficulties. Here is a non-functional sample using Vue.js for data binding within a script tag:

<HTML>
<HEAD>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="../static/css/zTreeStyle/zTreeStyle.css" type="text/css">
    <script type="text/javascript" src="../static/js/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="../static/js/jquery.ztree.core.js"></script>
    <script src="https://unpkg.com/vue"></script>
</HEAD>

<BODY>
    <div id="app">
        <TABLE>
            <TR>
                <TD width=260px valign=top>
                    <ul id="tree" class="ztree"></ul>
                </TD>
                <TD valign=top>
                    <p>{{ now }}</p>
                    <p>Some text</p>
                </TD>
            </TR>
        </TABLE>
        
        <SCRIPT type="text/javascript">
            var zTree;
            var setting = {
                data: {
                    simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "pId",
                    rootPId: ""
                    }
                }
            };
            var zNodes = [
                {id: 1, pId: 0, name: "root", icon:"../static/css/zTreeStyle/img/diy/c16green.png"},
                {id: 2, pId: 1, name: "leaf", icon:"../static/css/zTreeStyle/img/diy/c16red.png"},
                {id: 3, pId: 1, name: "foo", icon: {{ customIcon }} },
            ];
            $(document).ready(function () {
                var t = $("#tree");
                t = $.fn.zTree.init(t, setting, zNodes);
            });
        
            const app = new Vue({
                el: '#app',
                data: {
                    now: new Date(),
                    customIcon : "../static/css/zTreeStyle/img/diy/c16green.png"
                },
                methods: {
                    updateDate() {
                        this.now = new Date();
                    }
                },
                mounted() {
                    setInterval(() => {
                        this.updateDate();
                    }, 1000);
                },
            })
        </script>
    </div>
</BODY>
</HTML>

You can access the zipped sample containing these examples in the template directory here: https://drive.google.com/file/d/1Ihv8jLdsEz93aUrFjEugD1l6YvslaUT8

Answer №1

Here are the steps to solve the problem:

  1. Utilize "go-echo-vue" for communication between backend and frontend, as shown in this example: https://github.com/covrom/go-echo-vue

  2. Update zTree data using vue-resource and a timer by following this code snippet:

     <script>
     new Vue({
         // ....
         methods: {
             updateZNodes() {
                 // Request the tree :)
                 this.$http.get('/znodes').then(function (response) {
                     zNodes = response.data.items ? response.data.items : []
                 }, function (error) {
                     console.log(error)
                 });
             },
         },
         mounted() {
             setInterval(() => {
                 this.updateZNodes();
             }, 5000);
         },
         // ....
     })</script>
    
  3. Refresh zTree nodes information using JavaScript:

     <script language="JavaScript">
             function refreshNode() {
             var treeObj = $.fn.zTree.getZTreeObj("tree");
             var nodes = treeObj.getNodes();
             if (nodes.length > 0) {
                 for (let i = 0; i < nodes.length; i++) {
                     c = "static/css/zTreeStyle/img/diy/c16grey.png";
                     if (zNodes.length >= i) {
                         c = zNodes[i].icon
                     }
                     nodes[i].icon = c;
                     treeObj.updateNode(nodes[i]);
                 }
             }
         };
    
         const timerId = setInterval(
             () => {
                 refreshNode();
             },
             5000
         );
     </script>
    
  4. Add async zTree settings:

     <script language="JavaScript">
         var setting = {
             // ....
             async: {
                 enable: true,
                 url: "",
                 autoparam: ["id", "icon"],
                 datatype: "json",
             },
             // ....
         };
     </script>
    

This approach utilizes a Vue function http.get to fetch fresh data from the backend and makes use of a global JavaScript variable to access that data within both Vue code segments and JavaScript blocks.

For more information, visit:

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

Javascript: Executing a interval, delay, and another interval

My challenge is to reveal a list of elements one after another using setInterval for 5 seconds. However, I want to introduce a 60-second timeout after the 7th element and then continue the interval without repeating the timeout for every 7th element. Here ...

Implementing Autocomplete search with jQuery Chosen plugin - a step-by-step guide

CSS <select class="custom" id="company_hub" name="company_hub" style="width: 400px; display: none;"> <option>-Select Item-</option> </select> https://i.sstatic.net/x4YtN.png I attempted the following method but it was unsucces ...

There seems to be an issue with the v-select component where it is unable to

I am currently utilizing Vuetify in my project and encountering an issue. When I input data using v-select, it works fine. Editing the data also functions properly. However, the problem arises when I click on Edit as the selected element is not visible. ...

Applying the Active CSS class to a Bootstrap Carousel

I'm currently working with a bootstrap carousel that displays dynamic images fetched from a backend API. The challenge I'm facing is that I'm unable to set the active class for the individual slides. If I hardcode the active class, all slide ...

What is the best method for importing Bootstrap into SvelteKit?

I am currently working on a SvelteKit website. I have integrated Bootstrap 5 into my project by adding it to the app.html file provided by the SvelteKit Skeleton starter project: <!-- Bootstrap styles and javascript --> <link rel="stylesheet ...

Adding inline SVGs to a Nuxt 3 Vite project: A step-by-step guide

Hey there, I've been struggling with importing inline SVGs into my Nuxt3 Vite project. Any advice would be greatly appreciated. I discovered that using <img src="~/assets/images/icons/push-icon-chatops.svg" /> works, but I actually ne ...

Is there a way to execute Javascript in Django without revealing static files?

When setting up payments on my Django site using Stripe, I realized that the .js file is visible under Sources in the developer tools when inspecting elements on any browser. This presents a potential security risk as anyone can access this file. How can ...

Is there a way to have two SVG files displayed on a single HTML page at the same time

Currently, I am facing an issue with my graphs. I have a line graph and a boxplot, but the boxplot is appearing below the line graph when I want it to be next to it. Any suggestions on how I can achieve this layout? Thank you! I attempted to use 2 differe ...

How can I silence the warnings about "defaultProps will be removed"?

I currently have a next.js codebase that is experiencing various bugs that require attention. The console is currently displaying the following warnings: Warning: ArrowLeftInline: Support for defaultProps will be removed from function components in a futur ...

Ways to showcase a variable's value in conjunction with text using .html() method

Hello, I need assistance with printing a value in a popup window. Below is the code I am using: "code" $('#warning').html('<p style="font-size: 12px;padding-top: 13px;">The updated list value is <p>' + var11); https://i.s ...

What is the best way to initiate a Post/Get Request to NodeJS without causing a page refresh?

Struggling to run a NodeJS function after clicking a button? You're not alone. Ajax requests haven't been working for me either when it comes to running NodeJS functions. I've got a bash script that generates a JSON file which I want to par ...

Using ng-include destroys the styling of the dropdown menu in a bootstrap ul li format

Greetings! I am attempting to replicate the following code snippet that creates a basic dropdown menu using bootstrap: <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="fal ...

The significance of the "$=" or "?=" symbols in lit-element illustrations

I'm struggling to comprehend the purpose of ?= or $= in these two instances: First Example: Lit-Element README <div id="box" class$="${this.uppercase ? 'uppercase' : ''}"> <slot>Hello World</slot> </div> ...

Running a code from a plugin in Wordpress site

I am currently utilizing the "wp-video-lightbox" plugin for WordPress, which generates small floating boxes for my videos. I am interested in incorporating variables like http://www.example.com/?video3 to provide shortcuts similar to what YouTube offers. ...

The Safari browser is currently having trouble loading the data sent back from the server

After successfully developing and deploying my website carspeedyrental.com, I received reports from some clients indicating that the website does not display available cars on the iPhone Safari browser. Interestingly, when tested on various browsers on A ...

Chrome crashing due to toDataURL

Recently, I have been working on a Tile Renderer for three.js and so far, everything appears to be functioning correctly. The process is quite simple: a) It creates multiple cameras, b) Renders the scene using each camera c) Generates a 'toDataURL&a ...

The error message that keeps popping up is saying that it cannot access the property "username" as it is undefined

signup.js const SignupForm = () => { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const handleSignup = () => { fetch("/signup", { method: "post", header ...

Exploring the magic of VueJS: Implementing computed properties for "set/get" functionalities in tandem with Vue.Draggable and

Currently, I am in need of assistance with utilizing "Vue.Draggable". For the past two days, I have been struggling to properly update the draggable array. The main challenge lies in: Updating the draggable array using computed set/get functions Obtaini ...

The Transition Division Is Malfunctioning

I've encountered an issue where I am trying to move a div by adjusting its left property, but no transition is taking place. Regardless of the changes I make to my code, the result remains the same. Below is the current state of the code. Can anyone i ...

Using vue-loader version 15 with laravel-mix

Currently, I am in the process of updating the vue-loader in my Laravel project to version 15.2.1. After updating the dependencies and running npm run watch, an error prompts me to use VueLoaderPlugin. Following the official documentation's instructio ...