admin管理员组文章数量:1404621
I have wrapped (client-side) socket.io in a prototype class:
Chat.Client = Class.create();
Chat.Client.prototype = {
initialize: function() {
...
this.socket.on('message', this.on_message);
...
},
on_message: function(data) {
this.add_chat_message(data.something);
}
do_something: function(something) {
...
}
This does not work because 'this' in on_message will be 'SocketNamespace'. Traditionally I would work around this by just passing 'this' into the callback as an additional parameter, but because I am using socket.io, I cannot simply do this.
How can I solve this?
I have wrapped (client-side) socket.io in a prototype class:
Chat.Client = Class.create();
Chat.Client.prototype = {
initialize: function() {
...
this.socket.on('message', this.on_message);
...
},
on_message: function(data) {
this.add_chat_message(data.something);
}
do_something: function(something) {
...
}
This does not work because 'this' in on_message will be 'SocketNamespace'. Traditionally I would work around this by just passing 'this' into the callback as an additional parameter, but because I am using socket.io, I cannot simply do this.
How can I solve this?
Share Improve this question asked Apr 13, 2012 at 13:30 Daniel SloofDaniel Sloof 12.7k14 gold badges75 silver badges108 bronze badges1 Answer
Reset to default 10You can wrap it in another function:
initialize: function() {
// ...
var client = this;
this.socket.on('message', function(data) { client.on_message(data); });
In newer browsers (or Node.js) you can alternatively use a function on the Function
prototype called "bind":
this.socket.on('message', this.on_message.bind(this));
The "bind" function returns a function that, when called, will force the original function ("on_message") to be invoked with the given value as the this
value.
本文标签: javascriptOriginal 39this39 context with SocketIOStack Overflow
版权声明:本文标题:javascript - Original 'this' context with Socket.IO - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744831186a2627356.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论