【问题标题】:How to bind the event handler of socket.io (in nodejs) to my own scope?如何将socket.io(在nodejs中)的事件处理程序绑定到我自己的范围?
【发布时间】:2011-07-10 11:14:56
【问题描述】:

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

【问题讨论】:

    标签: javascript events scope node.js socket.io


    【解决方案1】:

    我已经在我的 YUI3 上下文中解决了这个问题

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

    感谢 Pointy 提供“绑定”一词。

    【讨论】:

      【解决方案2】:

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

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

      对“bind”的调用将返回一个函数,该函数将调用 您的 函数,以便将 this 设置为您传递的参数(在这种情况下,this 来自调用那个“init”函数)。

      edit — Chrome 的函数原型中有“bind()”,所以我想它在节点中可以正常工作。

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

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

      【讨论】:

      • 不幸的是我没有 Chrome 来测试它,它在 Firefox 中不起作用。还有其他方法吗?
      • 你也应该试试 Chrome - 它是一个不错的浏览器而且速度非常快 :-)
      • 可能是,但我知道仍在使用 IE6 的用户。我无法订购。
      • 但是你说你在你的nodejs 服务器中使用了socket.io - 现在你说它是需要这个的客户端代码?
      • 我的意思是“与”。所以我在服务器和客户端上都使用它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多