H
H
Hello America2015-02-21 23:18:24
JavaScript
Hello America, 2015-02-21 23:18:24

How to connect a new dynamically created element in DOM with socket.io in Node.js?

In the course of work, the user creates a new tree element in the DOM, tries to connect this element and socket.io, but nothing comes out, and when this element is static, then everything works. What is the problem? I use on the server side:

io.sockets.on('connection', function (socket) {
    // Клиент подключен
    socket.emit('chat', { zeit: new Date(), text: 'Теперь вы подключены к серверу!' });
    // Отправка текста клиентом
    socket.on('chat', function (data) {
    // Передача текста всем клиентам в чате
      io.sockets.emit('chat', { zeit: new Date(), name: data.name || 'Anonym', text: data.text, x: data.x, y: data.y });
    });
});

and on the client side:
//*******************SOCKET*************************
  // WebSocket
  var socket = io.connect();
  // Новое сообщение
  socket.on('chat', function (data) {
    var zeit = new Date(data.zeit);
    contentId.append(
      $('<li></li>').append(
        // Время дня
        $('<span>').text('[' +
          (zeit.getHours() < 10 ? '0' + zeit.getHours() : zeit.getHours())
          + ':' +
          (zeit.getMinutes() < 10 ? '0' + zeit.getMinutes() : zeit.getMinutes())
          + '] '
        ),
        // Имя
        $('<b>').text(typeof(data.name) != 'undefined' ? data.name + ': ' : ''),
        // Текст
        $('<span>').text(data.text))
    );
    // Прокрутка списка вниз
    //$('body').scrollTop($('body')[0].scrollHeight);
  });
  //*******************SOCKET*************************
//...
  // Отправка сообщения
  function senden(){
    // Чтение полей ввода
    var name = nameId.val();
    var text = editorId.val();
    //*******************SOCKET*************************
    // Отправка сокета
    socket.emit('chat', { name: name, text: text });
    //*******************SOCKET*************************
    // Установка пустого текста
    editorId.val('');
  }

Essentially, I need to dynamically create rooms and display a new message stream in them.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
SagePtr, 2015-02-22
@SagePtr

Maybe the contentId variable is not defined?

N
Nikolai Antonov, 2015-02-22
@my-nickname

I do not know the answer, but I had a similar problem with Ajax: when creating an element, handlers did not work dynamically. I decided this way: put the handler like this

$body.on('click', $myElem, function(){
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question