0

ストロフィと参加している部屋ごとにオブジェクトがあります。このオブジェクトには、この特定のルームのプレゼンス スタンザを処理する関数が含まれています。

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

しかし、mainRoom.presenceHandler()関数が Strophe によってスタンザによって呼び出されるとthis、関数内でスタンザ自体が参照され、mainRoomもはや参照されないため、mainRoom.

プレゼンス ハンドラ関数内からルーム オブジェクトの属性にアクセスする方法を教えてください。

4

2 に答える 2

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
  }
}
于 2011-11-11T09:00:06.860 に答える
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*/);
}

ハンドラーのクロージャに注意してください

于 2012-02-08T11:46:17.373 に答える