如何将socket.io的事件处理程序(在nodejs中)绑定到我自己的作用域?

koa*_*der 5 javascript events scope node.js socket.io

我在我的nodejs服务器中使用"socket.io".有没有办法在我的类/模块的范围内(在浏览器中)运行已注册的事件函数?

...
init: function() {
  this.socket = new io.Socket('localhost:3000'); //connect to localhost presently
  this.socket.on('connect', this.myConnect);
},
myConnect: function() {
  // "this.socket" and "this.f" are unknown
  // this.socket.send({});
  // this.f();
},
f: function() {
  // ...
}
...
Run Code Online (Sandbox Code Playgroud)

Poi*_*nty 16

认为 V8支持"bind()"函数:

this.socket.on('connect', this.myConnect.bind(this));
Run Code Online (Sandbox Code Playgroud)

对"bind"的调用将返回一个函数,该函数将调用您的函数,使其this设置为您传递的参数(在本例中,this从调用该"init"函数的上下文).

编辑 - "绑定()"在Chrome中的函数原型中,所以我想它在节点中工作正常.

以下是您可以在浏览器中尝试的内容(可以使用Chrome的功能):

 var f = (function() { alert(this); }).bind("hello world");
 f();
Run Code Online (Sandbox Code Playgroud)