I've got some Node.js going on with some functions in the document ready of jQuery. I have two files both of which have a document ready. However, one file calls to the other, and it doesn't recognize the function. ReferenceError: SocketGameOut is not defined
=========== File 1 =============
$(document).ready( function () {
var socket = io.connect('http://local.baseball.com:3333');
socket.on('news', function (data) {
SocketBroadcastIn(data);
});
socket.on('message', function (data) {
SocketGameIn(data);
});
function SocketGameOut(outstring) {
socket.emit('clientData', outstring );
}
});
============ File 2 ==============
$(document).ready( function () {
$("#login").click( function () {
var loginData = { command: 'login', user: $("#user").val(), pass: $("#password").val() }
var data = JSON.stringify(loginData);
SocketGameOut(data); <--This function call returns
ReferenceError: SocketGameOut is not defined
});
});
The functions follow the same scope rules as variables (in fact, functions are variables). So if you create a function within another function, it will be visible only in that function.
In the first file you do not need the $(document).ready
event, because you do not manipulate the DOM. Just remove it and create the variables in the global scope, so they will be visible in other parts of File 1 and in all files, included after this one.
Another way is to attach this function to a variable outside the $(document).ready
, so it will be in global scope, but it is unnecessary here and first way will be much better:
var SocketGameOut;
$(document).ready( function () {
//your code...
SocketGameOut = function (outstring) {
socket.emit('clientData', outstring );
}
//your code...
});