0

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

});

});
1
  • The easy way out would be to make SocketGameOut global. For instance, in file1, the last thing inside your document.ready, put window.SocketGameOut = SocketGameOut. Commented Aug 30, 2014 at 20:27

1 Answer 1

1

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...
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.