我有以下代码片段
var peer = {};
var foo = function ($scope, socket) { // socket is a factory to wrap socket.io in angular
socket.on('setUID', function (data) {
peer = new Peer(data);
});
};
var bar = function ($scope, socket) {
peer.on('connect', function () { alert("blah"); }); // this line doesn't work
}
// foo and bar are both controllers in angular, which are attached to separate areas in the application
本质上,我要做的是使用服务器生成的 ID 创建一个新的 PeerJS 对等体,一旦客户端连接,该 ID 就会使用 socket.io 传输。因此,我知道将在触发 on 侦听器之前创建对等对象。但是,我不认为 javascript 知道这一点。如何设置它以便我可以在我的控制器中使用对等方的未来功能?
编辑:这是我目前拥有的
app.factory('peer', function ($rootScope, socket) {
var peer = {};
socket.on('setUID', function (data) {
peer = new Peer(data, {host: 'localhost', port: 9000, path: "/peer/"});
console.log("Peer created");
peer.on('open', function (id) { // these work fine
console.log('My peer ID is: ' + id);
});
peer.on('connection', function (conn) {
conn.on('open', function () {
conn.on('data', function (data) {
console.log("Received: " + data);
});
});
});
});
return {
getPeer: function () {
return peer;
}
};
});
var bar = function ($scope, socket, peer) {
var p = peer.getPeer();
p.on("connection", console.log("hello")); // works once, then says p.on is not a function
}