我试图将peerJS“发布”函数分配给按钮单击事件,但它不会将消息发送到其他浏览器页面。
如果我直接调用发布函数而不是通过单击事件,我会在其他浏览器上收到一条消息。
发送方代码:
<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>
接收端代码:
<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>
最佳答案
好吧,
问题解决了!我需要重构我的代码并在对等连接 block 内声明 publish()
函数。
以下是将功能分配给按钮的代码:
<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>
关于javascript - 将peerJS函数分配给按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23523338/