如何在JS对象之间共享websocket连接?

时间:2019-05-30 18:24:01

标签: javascript websocket

如何在不同的JS对象之间共享Websocket连接?我有一个网页,它会在登录时自动通过登录提示连接到套接字。登录成功后,我将隐藏登录UI,并使应用程序UI可见,并通过在小部件构造函数中传递我自己的数据Feed来加载图表小部件(tradingview)。现在的问题出在小部件中,因为它没有对websocket的引用,而且似乎也没有将它作为参数传递的方法。

注意:刚开始JS / Web编程。为我指出正确的方向非常感激。

wsfeed.js

var settings_symbols = {};
var webSocket = new WebSocket('ws://localhost:8080/api');
webSocket.onmessage = function processMessage(evt)
{   
 var json = evt.data; 
 wsMsgHandler(json);
}

function wsMsgHandler(jsonResponse)
{
    jsonResponse = JSON.parse(jsonResponse);

    try
    {
        if(jsonResponse.length>0)
        {
            if(jsonResponse.API[0].event == "login")
            {
                if(jsonResponse.API[0].cmd=="settings" && jsonResponse.API[0].result=="success")
                {
                settings_symbols =jsonResponse.API[0].symbols;

                }
                doChartLoad(settings_symbols, webSocket);

            }
        }

    }catch(err)
    {


    }

}

function doChartLoad(settings_symbols, webSocket)
{
     var config = {
            debug:true,
            exchanges:["forex","stock","crypto"],
            symbols_types:[],
            supported_resolutions:[],
            supports_marks:false,
            supports_timescale_marks:false,
            supports_time:false,
            futures_regex:'/^(.+)([12]!|[FGHJKMNQUVXZ]\d{1,2})$/',
            }
            config.symbols=lstSymbols;

    new TradingView.widget({
        symbol: 'A',
        interval: 'D',
        timezone: "America/New_York",
        container_id: "tv_chart_container",
        locale: "ru",
        datafeed: new DatafeedEndpoint(config, webSocket),
        library_path: "charting_library/",
    });

}

class DatafeedEndpoint
{
    constructor(options, webSocket)
    {
    this.webSocket = webSocket;
    }
        onReady() {console.log("TV::onReady"); wsChartLoaded();}
        searchSymbols() {console.log("TV::searchSymbols");}
        resolveSymbol() {console.log("TV::resolveSymbol");}
        getBars() {console.log("TV::getBars");}
        subscribeBars() {console.log("TV::subscribeBars");}
        unsubscribeBars() {console.log("TV::unsubscribeBars");}

        wsChartLoaded()
        {
            try
            {
                this.webSocket.send(JSON.stringify({'cmd' : 'chart_loaded'}));

            }catch (err)
            {
                console.log(err.Name);          // ReferenceError
            }

        }

}

0 个答案:

没有答案