[英]What might be wrong with my class?
I am working on a class to have callbacks to a web socket: 我正在上一个类,以回调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;
}
Then I use it in this sample: 然后在此示例中使用它:
<!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>
I do not get any of the alerts and I should be getting at least one of them. 我没有收到任何警报,我应该至少收到其中一个。 I checked in Chrome and my qb is correctly created and its ws variable has the callbacks hooked to it and the qb has the callbacks I set.
我在Chrome中签入,并正确创建了我的qb,并且其ws变量具有与之关联的回调,而qb具有我设置的回调。
I cannot figure out why this is not working. 我不知道为什么这不起作用。
Thanks 谢谢
The this
scope inside the anonymous functions is not the this
of your QB instance: 在
this
范围内的匿名函数里面是不是this
你的QB实例:
ws.onopen = function () {
if (this.onConnectionEstablished) {
this.onConnectionEstablished()
}
};
It should work like so: 它应该像这样工作:
var self = this;
ws.onopen = function () {
if (self.onConnectionEstablished) {
self.onConnectionEstablished()
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.