node.jssocket.iosails.jssails.io.js

how to emit a message from browser when using Sails.io.js


Before I would just

<script>
var socket = io.connect(URL);
socket.emit("hello", {});
</script>

Using Sails.io.js, I tried io.sails.emit("myevent", jsonData) ... but can't do that:

io.socket.emit is not a function

So I do you actually emit a message to the websocket (from the browser) to the room you have joined?

What am I missing?

http://sailsjs.org/documentation/reference/web-sockets/socket-client


Solution

  • Currently there is no method .emit() in sails.socket.

    You should use .get(), .post(), .put(), or .delete().

    How to use it:

    instead of

    socket.emit('eventName', jsonData)
    

    now you use:

    socket.get('routeToController', jsonData, callback);
    

    Example:

    You can create controller SocketController.js

    module.exports = {
        myevent: function(req, res) {
            res.json({
                value: 1
            });
        }
    };
    

    in config/routes.js add:

    'GET /socket/myevent': 'SocketController.myevent'
    

    and now you can call:

    socket.get('/socket/myevent', jsonData, function(error, data){
        //data = {value: 1}
    });