Search code examples
javascripthtmlpeerjs

Assign a peerJS function to a button


I'm trying to assign a peerJS "publish" function to a button click event, but it doesn't send the message to other browser pages.

If I call the publish function directly and not by click event, I get a message on the other browser.

sender-side code:

<body>
    <script>
        var peer = new Peer('controller', {key: 'xxxxxxxxxxxxxxx'});
        var conn = peer.connect('game');
        
        function publish(m) {
            conn.on('open', function(){
                conn.send(m);
            }); 
        };
    
        //This is working:
        publish("It's working 😄");
    
    </script>

    <button onclick="publish('Not working 😞')">send</button>
</body>

Receiver-side code:

<script>
    var peer = new Peer('game', {key: 'xxxxxxxxxxxx'});
        peer.on('connection', function(conn) {
            conn.on('data', function(m){
            // Will print the value of (m)
            console.log(m);
        });
    });
</script>

Solution

  • Alright, problem solved! I needed to refactor my code and declare the publish() function inside the peer connection block.

    here's the code to assign the function to the button:

    <script>
        $( document ).ready(function() {
            var peer = new Peer('controller', {key: 'xxxxxxxxxx'});
            var conn = peer.connect('myGame');
            var publish;
            
            conn.on('open', function(){
                publish = function(message) {
                    conn.send(message);
                }
            }); 
        })
    </script>
    

    HTML

    <button onclick="publish('Now I'm working!')">Send<button>