this reference in Strophe stanza handlers
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 mainRo开发者_StackOverflowom
.
Could you tell me, how I can access the attributes of the room object from within the presenceHandler function?
try initializing the main class again inside the function ...
function MainFunc() {
this.method1 = function() {
this.property1 = "foo";
}
this.method2 = function() {
var parent = this; // assign the main function to a variable.
parent.property2 = "bar"; // you can access the main function. using the variable
}
}
this.join = function() {
connection.addHandler(this.presenceHandler,null,"presence",null,null,this.name);
connection.send(/*presence*/);
}
Replace above code with this
var thiss=this;
this.join = function() {
connection.addHandler(function(presence)
{thiss.presenceHandler(presence);},null,"presence",null,null,this.name);
connection.send(/*presence*/);
}
note the closures for the handler
精彩评论