3

In my application i have created many methods in node.js file.How can i call the particular method from client side javascript.

Below is my node.js file

        exports.method1=function(){

          }

        exports.method2=function(){

          }

         exports.method3=function(){

          }
1
  • You'd have to do it using AJAX, or an RPC such as: NowJS, or DNode. Commented Mar 12, 2013 at 10:51

2 Answers 2

3

Your client should send a message, for example:

socket.emit("callMethod", {"methodName":"method3"});

And in your server:

socket.on("callMethod", function(data) {
    if(data["methodName"] == "method3") {
        exports.method3();
    }
});

You don't call methods directly, you send events/messages.

Sign up to request clarification or add additional context in comments.

1 Comment

For the people that would want more information regarding socket.io
0

I would avoid using sockets unless you really need to, from my experience they can be expensive. Sockets are great for intensive applications where a user stays engaged for awhile, otherwise I would suggest using a RESTful setup with javascript and node.js, for example:

http://blog.modulus.io/nodejs-and-express-create-rest-api

this way the socket doesn't always have to be open which causes more overhead anyway. REST will use http requests whereas sockets you will have direct connection via TCP. REST is better if your app won't be constantly engaging a user, but rather have updates here and there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.