我正在创建一个类来回调Web套接字:
function QB() {
var ws = null;
this.connect = function () {
// Let us open a web socket
ws = new WebSocket("ws://localhost:9000/koule");
ws.onopen = function () {
if (this.onConnectionEstablished) {
this.onConnectionEstablished();
}
};
ws.onmessage = function (evt) {
var msg = evt.data;
//process callbacks
parseMessage(msg);
};
ws.onclose = function () {
if (this.onConnectionClosed) {
this.onConnectionClosed();
}
};
ws.onerror = function () {
if (this.onConnectionError) {
this.onConnectionError();
}
};
};
this.onConnectionEstablished = null;
this.onConnectionClosed = null;
this.onConnectionError = null;
}
然后我在这个样本中使用它:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="qb.js"></script>
</head>
<body>
<h1>My First JavaScript</h1>
<p>Click Date to display current day, date, and time.</p>
<button type="button" onclick="myFunction()">Date</button>
<p id="demo"></p>
<script>
qb = new QB();
qb.onConnectionEstablished = function()
{
alert('connected');
};
qb.onConnectionError = function()
{
alert('error');
};
qb.onConnectionClosed = function()
{
alert('closed');
};
function myFunction() {
qb.connect();
}
</script>
</body>
</html>
我没有得到任何警报,我应该至少得到其中一个。我在Chrome中检查了我的qb是否已正确创建,其ws变量将回调挂钩到它并且qb具有我设置的回调。
我无法弄清楚为什么这不起作用。
由于
答案 0 :(得分:2)
匿名函数中的this
范围不是QB实例的this
:
ws.onopen = function () {
if (this.onConnectionEstablished) {
this.onConnectionEstablished()
}
};
应该这样工作:
var self = this;
ws.onopen = function () {
if (self.onConnectionEstablished) {
self.onConnectionEstablished()
}
};