5

我在我的 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() {
  // ...
}
...
4

2 回答 2

16

认为V8 支持“bind()”功能:

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

对“bind”的调用将返回一个函数,该函数将调用您的函数,该函数this设置为您传递的参数(在这种情况下,this从调用的上下文到该“init”函数)。

编辑— Chrome 的函数原型中有“bind()”,所以我想它在 node.js 中可以正常工作。

以下是您可以在浏览器中尝试的内容(具有可用功能的浏览器,例如 Chrome):

 var f = (function() { alert(this); }).bind("hello world");
 f();
于 2011-03-07T16:17:16.943 回答
3

我已经在我的 YUI3 上下文中解决了它

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

感谢 Pointy 的“绑定”一词。

于 2011-03-07T17:27:32.393 回答