signalr 客户端不会触发点击侦听器

signalr client doesn't fire on click listener

过程是:点击.post-thread时,通过hub调用服务器,returns一个<p data-id = id class = 'take-thread'>,追加到foodiv.然后我点击 <p>,它应该在服务器端 运行 TakeThread

但是,当我单击新添加的 <p> 时,console.log('test') 不会触发,直到我在星形矩形中添加了代码。我不明白为什么。 Hub.start().done() 中已经有一个侦听器来触发点击。为什么我必须在集线器客户端功能中执行此操作?

JS:

var chat = $.connection.chatHub;
chat.client.updateThings(id){
   $('.foo').append('<p data-id = "id" class = "take-thread"></p>');

   // Why do I need to these code below?  
   ************************************************  
   * $('.take-thread').on('click', function () {  *
   *     console.log("test");                     *   
   *     chat.server.takeThread("blah...");       * 
   * });                                          * 
   ************************************************

}

$.connection.hub.start().done(function () {
    $('.post-thread').on('click', function () {
        chat.server.postThread("Test"); // works
    });
    $('.take-thread').on('click', function () {
        console.log("test");
        chat.server.takeThread("blah..."); 
    });
}     

C# 中心:

public void PostThread(string title) {
    var id = someCalculation();
    Clients.All.updateThings(id);
}

public void TakeThread(string title) {
    // do things
}

这是一个绑定问题。调用 document.ready 后添加到页面的动态元素不会自动获得反弹。这就是您将第二个单击事件添加到 updateThings 函数时所做的事情。

您需要 .on() 我们 document.ready (.foo) 上的静态 parentSelector 以及由 SignalR 回调添加的动态元素的选择器 (.take-thread).

请参阅此示例,使用标准警报代替 SignalR:http://jsfiddle.net/kspearrin/0zyoqyxL/

最后,您的 Javascript 应更新为以下内容:

var chat = $.connection.chatHub;
chat.client.updateThings(id){
   $('.foo').append('<p data-id="id" class="take-thread"></p>');
}

$.connection.hub.start().done(function () {
    $('.post-thread').on('click', function () {
        chat.server.postThread("Test"); // works
    });

    $('.foo').on('click', '.take-thread', function () {
        console.log("test");
        chat.server.takeThread("blah..."); 
    });
}