У меня проблемы с пониманием, что означает этот фрагмент кода JavaScript. Может кто-то давать комментарии построчно?
Я знаю, что он должен взять текст и отправить его в каждый сокет, но я не уверен, что делает каждая строка.
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
2 ответа
$(function() {
// create a new socket which connects to `/` by default
var socket = io()
// add a submission handler to any form on the current page
$("form").submit(function() {
// emit the value stored in the element identified by the id `m` as an argument for the `chat message` event in socket io
socket.emit("chat message", $("#m").val())
// clear the value stored in `#m`
$("#m").val("")
// prevent event propagation
return false
})
})
Я бы сказал, что этот код немного некорректен, так как он будет срабатывать при любой отправке формы - если у вас будет несколько форм, у вас будут проблемы:)
// When the document is ready
// jQuery shortcut for $(document).ready(function() {
$(function() {
// create a new socket and assign it to the socket variable
var socket = io();
// when the form is submitted
$('form').submit(function() {
// emit a "chat message" event containing the value
// of of the element with the `m` id
socket.emit('chat message', $('#m').val());
// set that element's value to empty string
$('#m').val('');
return false;
});
});