在页面刷新之前未调用SignalR客户端功能

时间:2013-05-13 14:43:59

标签: javascript jquery asp.net-mvc signalr

我有一个asp.net mvc视图,其中包含使用以下代码动态加载的一些部分:

$('#div1').load('controller1/action1', function() {
    alert('Load was performed.');
});

$('#div2').load('controller1/action2', function() {
    alert('Load was performed.');
});

加载的所有视图都将使用signalr连接。我无法多次启动连接,如下所示:

$.connection.hub.start().pipe(test).done(function () {
    //....
});

我收到错误:

*SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started.*

因此我将start方法的返回值存储在全局变量中:

<script type="text/javascript">
    window.connection = $.connection.hub.start();
</script>

我正在使用它如下:

$(document).ready(function () {

var initialMarketWatchData = null;
var marketWatchTicker = $.connection.marketWatch;

function initMarketWatch() {
    return marketWatchTicker.server.getAllMarketWatchData().done(function (data) {
        data.forEach(function (item) {
            item.ask = item.ask.toFixed(5);
            item.bid = item.bid.toFixed(5);
        });
        initialMarketWatchData = data;
        $("#marketWatchGrid").data("kendoGrid").dataSource.data(data);
    });
}

marketWatchTicker.client.updateMarketWatchData =
    function (marketWatchData) {
        try {
            if (viewModelOrder.selectedInstrument == marketWatchData.symbol) {
                viewModelOrder.updatePrice(marketWatchData.ask.toFixed(5), marketWatchData.bid.toFixed(5));
            }

            var tr = $("#marketWatchGrid").find("tr:contains('" + marketWatchData.symbol + "')");
            var bg = '';
            if (marketWatchData.direction == 1) {
                bg = '154,240,117';
            }
            else {
                bg = '255,148,148';
            }

            tr.find("td:nth-child(2)").html(marketWatchData.ask.toFixed(5));
            tr.find("td:nth-child(3)").html(marketWatchData.bid.toFixed(5));

            var current = tr.css('backgroundColor');
            tr.animate({ backgroundColor: 'rgb(' + bg + ')' }, 150)
                .animate({ backgroundColor: current }, 150)
        } catch (e) {
            console.log("exception: " + e.message);
        }
    }

window.connection.pipe(initMarketWatch).done(function () {
    viewModelHomeIndex.setInstruments(initialMarketWatchData);
});

});

function selectSymbol(symbol) {
    var tr = $("#marketWatchGrid").find("tr:contains('" + symbol + "')");
    var ask = tr.find("td:nth-child(2)").html();
    var bid = tr.find("td:nth-child(3)").html();
    viewModelOrder.selectSymbol(symbol, ask, bid);
}

但在这种情况下,我的客户端函数在第一次加载视图时没有被调用。而且我没有收到任何错误。我点击F5后一切正常。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我找到了另一个问题的答案:https://stackoverflow.com/a/15074002/104969 它解决了我的问题。