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

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

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

认为 V8支持“bind()”function:

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

对“绑定”的调用将返回一个函数,它会调用你的函数,使得this被设置为你传递的参数(在这种情况下, this从调用上下文到“init”函数)。

编辑 – “绑定()”在Chrome中的函数原型,所以我想它在节点中工作正常。

以下是您可以在浏览器中使用的function(例如Chrome)。

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

我用我的YUI3上下文解决了它

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

感谢Pointy为“绑定”一词。