1

I have a problem with button click does not firing when it dynamically created,

I know, here is the solution.

Question is this:

I am using SignalR. I must declare click event (to call some hub method) when chat hub is started. Please see below

button click works in this situation

  $(document).on('click', "#chatlist li .gobtn", function (e) {
            var id = $(this).closest("li").data("message-id");
        }); 

But i should call it from here

$.connection.hub.start().done(function () {
      //button click not fires here but it must be here
     $('#chatlist li .gobtn').click(function () {
      var id = $(this).closest("li").data("message-id");
      chat.server.sendAnswer(id);
      })
    })

Please help if you have any idea to solve it.

Community
  • 1
  • 1
Emin Hasanov
  • 1,299
  • 1
  • 13
  • 29
  • Not sure I get it. In the `done()` function you're trying to call a click on a button with a *class* - `.gobtn` - to pass the `message-id`. If the buttons all use the same class, which button you're triggering the click on? In other words, what is `$(this)` when you get to its `data` attribute when the hub starts? Is the hub starting done once, as an initialization? – lesssugar Mar 14 '15 at 23:24
  • check this solution http://stackoverflow.com/questions/20819501/jquery-click-event-not-working-for-dynamically-created-button – Murad Garibzada Mar 15 '15 at 18:25
  • @lesssugar there are many buttons with same class, this event can fire for each of them. $this will be clicked button – Emin Hasanov Mar 15 '15 at 20:02
  • @MuradQaribov at the top of question i wrote about this fix. I need to declare event when chat hub is done – Emin Hasanov Mar 15 '15 at 20:03

1 Answers1

1

If you change your code like below, i think it works

    var chat;
var _sendAnswer;
$(function () {
    var chat = $.connection.chatHub;
    $.connection.hub.start().done(function () {
        _sendAnswer = function sendAnswer(id) {
            chat.server.sendAnswer(id);
        }
    });

    $(document).on('click', "#chatlist li .gobtn", function (e) {
        var id = $(this).closest("li").data("message-id");
        if (_sendAnswer != undefined && typeof _sendAnswer == 'function') {
            _sendAnswer(id);
        }
    }); 
});

I wish you good luck