Skip to content Skip to sidebar Skip to footer

Socket Js Not Works Inside Onload Method

I have this js piece which I use for django channels: var chatSocketSender1 = new WebSocket( 'ws://' + window.location.host + '/ws/my_socket1/' ) function send() { var ms

Solution 1:

The reason your code doesn't work is because in your first code var chatSocketSender1 creates a "global" variable (that's defined at the window level) that you later reference as window("chatSocketSender1"), but in the second code, var chatSocketSender1 is scoped to the anonymous event handler function, so is not available as window("chatSocketSender1").

Put another way:

<script>var x = 1;
functionfoo() {
 console.log(x)
}
</script>

works fine, but

<script>functionfoo() {
  var x = 1;
}
foo();
console.log(x);
</script>

will give an undefined variable error as x only exists inside foo. This isn't exactly what you've done, but is essentially the same concept.

Now, if your code was:

chatSocketSender1.send(

then it would have worked fine as your variable chatSocketSender1 is defined within the function() { onload event callback.

or instead of

var chatSocketSender1 =

you could do

window.chatSocketSender1 =

to define the variable globally, or you could:

<script>var chatSocketSender1 = newWebSocket(...
functionsend() { ... }
$(window).on('load', function () {
  document.querySelector('#send_button').onclick = ...

as you generally only need the event binding within the onload.

Post a Comment for "Socket Js Not Works Inside Onload Method"