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

时间:2011-03-07 16:12:51

标签: 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() {
  // ...
}
...

2 个答案:

答案 0 :(得分:16)

认为 V8支持“bind()”函数:

this.socket.on('connect', this.myConnect.bind(this));

对“bind”的调用将返回一个函数,该函数将调用您的函数,以便将this设置为您传递的参数(在本例中为this调用“init”函数的上下文。

编辑 - Chrome中的Function原型中有“bind()”,所以我想它在节点中工作正常。

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

 var f = (function() { alert(this); }).bind("hello world");
 f();

答案 1 :(得分:3)

我已经在我的YUI3环境中用

解决了这个问题
this.socket.on('connect', Y.bind(this.myConnect, this));

感谢Pointy的“bind”这个词。