Strophe节处理程序中的这个引用

时间:2011-09-10 12:50:07

标签: javascript strophe

我为Strophe加入的每个房间都有一个对象。此对象包含用于处理此特定房间的存在节的函数。

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();

但是当Strophe的一个节调用mainRoom.presenceHandler()函数时,函数中的this引用了节本身而不再指向mainRoom,所以我无法访问mainRoom

你能告诉我,我如何从presenceHandler函数中访问房间对象的属性?

2 个答案:

答案 0 :(得分:1)

尝试在函数内再次初始化主类...

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
  }
}

答案 1 :(得分:0)

        this.join = function() {
    connection.addHandler(this.presenceHandler,null,"presence",null,null,this.name);
    connection.send(/*presence*/);
}

将上述代码替换为此

        var thiss=this;
    this.join = function() {
    connection.addHandler(function(presence)             
    {thiss.presenceHandler(presence);},null,"presence",null,null,this.name);
    connection.send(/*presence*/);
}

请注意处理程序的闭包