2017-08-10 2 views
0

サーバーが受け取ったパラメータに基づいて、さまざまなjavascript関数(サーバーからクライアントへ!)を呼び出そうとしています。signalRを使用してハブから特定の関数を呼び出す方法

サーバーからクライアントサイドで呼び出すパラメータの関数を指定するにはどうすればよいですか。クライアント上の

public class TestData 
{ 
    public string function{ get; set; } 
    public string element{ get; set; } 
} 

public class PerfHub : Hub 
{  
    public void Send(string id, string message) 
    { 
     if (!String.IsNullOrEmpty(id)) 
     { 
      List<TestData> testList = new List<TestData>(); 
      if (id == "1") 
      { 
       testList.Add(new TestData { function= "show", element= "grid" }); 
       Clients.All.sendInstructions(id, testList); 
      } 
      else if (id == "2") 
      { 
       testList.Add(new TestData { function= "hide", element= "grid" }); 
       Clients.All.sendInstructions(id, testList); 
      } 

私JavaScriptは次のようになります。

$(function() { 

    var instructions = $.connection.perfHub; 

    // receive instructions from the server 
    instructions.client.sendInstructions = function (id, message) { 


     var requestedFunction = message; 

     function show(parameters) { 
      $(parameters).show(); 
     } 

     show(); 

     function hide(parameters) { 
      $(parameters).show(); 
     } 

     hide(); 

は現在、私は私が正しく動作するには、イベントをクリックして取得するように見えることができないようにjQuery .hover方法を使用してサーバにIDを送信します。

$.connection.hub.start().done(function() { 
     $('html *').hover(function() { 
      // Call the Send method on the hub. 
      instructions.server.send($(this).attr('id'), $(this).val()); 
      //$('#message').val($(this).attr('id')).focus(); 
     }, function() { 
      $('#message').val('').focus(); 
     }); 
    }); 
}); 

ありがとうございます!

+0

あなたが得るエラーは何ですか?実際に何が起こるのですか? Clients.All.sendInstructions(id、testList);クライアント上でsendInstructionsという関数を呼び出す正しい方法です – reckface

答えて

1

動的キーを使用して修正しました。

var instructions = $.connection.perfHub; 

    instructions.client.sendInstructions = function (id, message) { 

     if (id === "serverFunction") { 

      var ctx = { 
       showRoads: function (param) { $(param).show(); }, 
       hideRoads: function (param) { $(param).hide(); }, 
       shoresOn: function (param) { $(param).show(); }, 
       shoresOff: function (param) { $(param).hide(); }, 
       showTiles: function (param) { $(param).show(); }, 
       sideTiles: function (param) { $(param).hide(); } 
      } 

      for (var index = 0; index < message.length; ++index) { 
       ctx[message[index].function](message[index].element); 
      } 

     } 
    } 

    // Call the Send method on the hub. 
    $.connection.hub.start().done(function() { 
     $('html *').click(function() { 
      instructions.server.send($(this).attr('id'), $(this).val()); 
     }); 
    }); 

これは人々のために有用で来る、それは間違いなく私のためにやった希望:)

関連する問題