Strope 节处理程序中的此引用
我为每个要加入 Strope 的房间准备了一个对象。该对象包含一个用于处理该特定房间的存在节的函数。
function Room(name, someData)
this.name = name;
this.someData = someData;
this.presenceHandler = function(presence) {
console.log(this.name, this.someData);
}
this.join = function() {
connection.addHandler(this.presenceHandler,null,"presence",null,null,this.name);
connection.send(/*presence*/);
}
}
var connection = new Strophe.Connection(/*http-bind*/);
var mainRoom = new Room("main", {foo: "bar"});
mainRoom.join();
但是,当 Strope 的节调用 mainRoom.presenceHandler()
函数时,函数中的 this
指的是节本身,而不是 mainRoom
不再存在,所以我无法从 mainRoom
访问属性。
您能告诉我,如何从 PresenceHandler 函数中访问房间对象的属性吗?
I have an object for each room I'm joining with Strophe. This object contains a function for handling presence stanzas for this particular room.
function Room(name, someData)
this.name = name;
this.someData = someData;
this.presenceHandler = function(presence) {
console.log(this.name, this.someData);
}
this.join = function() {
connection.addHandler(this.presenceHandler,null,"presence",null,null,this.name);
connection.send(/*presence*/);
}
}
var connection = new Strophe.Connection(/*http-bind*/);
var mainRoom = new Room("main", {foo: "bar"});
mainRoom.join();
But when the mainRoom.presenceHandler()
function is called by an stanza by Strophe, this
in the function refers to the stanza itself and not to mainRoom
anymore, so I cannot access the attributes from mainRoom
.
Could you tell me, how I can access the attributes of the room object from within the presenceHandler function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试在函数内再次初始化主类...
try initializing the main class again inside the function ...
将上面的代码替换为
处理程序的闭包注释
Replace above code with this
note the closures for the handler