Advanced

WebSockets (Custom Proxy)

To provide live updates in real-time apps (e.g. live chats), use a Websocket-based solution.

General Principles for Data Components

The initial data are loaded into a data component without the socket. You need to tune sockets only for data updates:

const socket = new WebSocket("ws:host");

To send data to the server side, use the onStoreUpdated event and the socket.send() method:

$$("data").data.attachEvent("onStoreUpdated", (id, update, operation) => {
    socket.send(webix.stringify(update));
});

To update data on the client, use socket.onmessage(), keeping in mind that you need to wrap data updates into DataProcessor.ignore() to avoid unnecessary saving to the server side.

socket.onmessage = (e) => {
    var update = webix.DataDriver.json.toObject(e.data);
 
    webix.dp(view).ignore(() => {
        // update view data
        // ...
    });
};

This is the complete solution as a custom proxy that opens a socket, takes care of receiving data updates and closes the socket when it is no longer necessary:

//declare
webix.proxy.socket = {
    $proxy:true,
    load:function(view) {
        //create a socket connection
        this.socket = new WebSocket("ws:"+this.source);
 
        //handle errors
        this.socket.onerror = (error) => {
            console.log("WebSocket Error", error);
        };
        //receive updates
        this.socket.onmessage = (e) => {
            // update view data
            // ...
        };
        //close a socket connection when a view is destroyed
        view.attachEvent("onDestruct", () => {
            this.socket.close();
        });
    },
    save:function(view, update) {
        //send message to server
        this.socket.send(webix.stringify(update));
    }
};

Now you can define the proxy and use it for live updates in a data component, e.g.:

//define a common proxy for loading and saving with unique clientId and key
var data_proxy = webix.proxy("socket", "//localhost:8080", {
    key:"data", clientId:webix.uid()
});
 
//use the proxy
webix.ui({
    view:"datatable",
    url:data_proxy,
    save:data_proxy
});

These are the basics of creating a Websocket-based solution for live updates in applications, for details please read the detailed tutorial in the Webix blog.

You can view the live demo by the link below or open the demo in the package (to set up the demo, run node backend/index.js).

Back to top