2012-09-12 46 views
7

用了这个错误的贴2小时挣扎..

TypeError: $.connection is undefined 
[Break On This Error] 

var chatHubClient = $.connection.chatHub; 

这里是我的Chat.cs(这是在控制器中的文件夹 - 我的猜测是这是我在做什么错的,但我找不到在哪里把它或任何文件如何路由吧)

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using SignalR.Hubs; 

namespace SingalrTest.Controllers 
{ 
    public class Chat 
    { 
     private readonly static Lazy<Chat> _instance = new Lazy<Chat>(() => new Chat()); 

     public static Chat Instance 
     { get { return _instance.Value; } } 
    } 

    [HubName("chatHub")] 
    public class ChatHub : Hub 
    { 
     private readonly int TimeoutInSeconds = 30; 
     private readonly Chat _chat; 

     public ChatHub() : this(Chat.Instance) { } 

     private ChatHub(Chat chat) 
     { 
      this._chat = chat; 
     } 

     public void Join(string channelName) 
     { 
      System.Diagnostics.Debug.WriteLine("Someone joined " + channelName); 
     } 
    } 
} 

,最后,在..可能_Layout.cs.html

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <meta charset="utf-8" /> 
     <title>@ViewBag.Title - My ASP.NET MVC Application</title> 
     <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" /> 
     <meta name="viewport" content="width=device-width" /> 

     @Styles.Render("~/Content/css") 
     @Scripts.Render("~/bundles/modernizr") 
     @Scripts.Render("~/Scripts/jquery-1.8.1.js") 
     @Scripts.Render("~/Scripts/jquery.signalR-0.5.3.js") 
     @Scripts.Render("~/signalr/hubs") 

     <script type="text/javascript"> 
      $(document).ready(function() { 
       // var chatHubClient = jQuery.connection.chatHub; 
       var chatHubClient = $.connection.chatHub; 

       $.connection.chatHub.start(function() { 
        chatHubClient.join('TEST'); 
       }); 
      }); 
     </script> 
    </head> 
    <body> 
    ... 
    </body> 
</html> 

如果我访问/ signalr /集线器,我可以看到源生成正确。那么我错过了什么?

+0

我有这个相同的问题。出于某种原因,$ .ready事件发生时未定义$ .connection。 我通过运行内联代码而不是就绪事件来修复它...我不知道它为什么会消失,虽然... –

回答

0

this,对于0.5.3版本,你必须改变连接语法:

var connection = $.hubConnection(); 

或引导用户访问辅助服务器

var connection = $.hubConnection("http://localhost:58416/"); 

连接到集线器:

var hub = connection.createProxy('your_hub_name'); 

还有一些更改发送和接收消息以及

希望这有助于

8

你可能已经转移...

但这里有一个解决方案。

您将所有脚本以正确的顺序放在head标签中。但是Visual Studio模板中的_Layout.cshtml在body标签的末尾有以下几行代码。

@Scripts.Render("~/bundles/jquery") 
@RenderSection("scripts", required: false) 

这个包有jQuery库,它在加载时覆盖$对象。所以SignalR的这个设置中的任何'东西'现在都被覆盖并且不可访问。

只需在页面中使用以下内容。

@section scripts { 
    @* Load your scripts here. (and remove jQuery, coz it's already loaded) *@ 
} 

希望这会有所帮助。

+0

真棒,非常感谢。 –

+0

虽然jquery在加载时会不会正确绑定?我宁愿让捆绑程序加载jQuery作为捆绑包的一部分,然后重新运行signalR的东西。 –

+0

是的。你只需要加载SignalR。并确保你在jQuery之后加载它。 (脚本部分在加载jQuery脚本之后运行,脚本在默认配置之前运行..) – Madushan