最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to bind the event handler of socket.io (in nodejs) to my own scope? - Stack Overflow

programmeradmin3浏览0评论

I'm using "socket.io" in my nodejs server. Is there a way to run the registered event functions in the scope of my class/module (in the browser)?

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

I'm using "socket.io" in my nodejs server. Is there a way to run the registered event functions in the scope of my class/module (in the browser)?

...
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() {
  // ...
}
...
Share Improve this question edited Mar 7, 2011 at 16:35 koalabruder asked Mar 7, 2011 at 16:12 koalabruderkoalabruder 2,9049 gold badges35 silver badges45 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 16

I think V8 supports the "bind()" function:

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

The call to "bind" will return a function that will call your function such that this is set to the argument you pass (in this case, this from the context of the call to that "init" function).

edit — "bind()" is there in the Function prototype in Chrome, so I imagine it works fine in node.

Here's what you can try in a browser (one that's got the function available, like Chrome):

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

I have solved it in my YUI3 context with

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

Thanks to Pointy for the word "bind".

发布评论

评论列表(0)

  1. 暂无评论