简体   繁体   English

Ecma6类事件处理程序

[英]Ecma6 Class Event handler

I was wondering how I could add a Eventhandler in a Ecma6 class. 我想知道如何在Ecma6类中添加Eventhandler。 The following example works, but I would like the event handlers in the class itself. 以下示例有效,但我希望类本身具有事件处理程序。

Here the code for the Class 这是该类的代码

class Bot {
constructor(username,password,shared_secret,identity_secret,bot_number) {
    this._username = username;
    this._password = password;
    this._shared_secret = shared_secret;
    this._identity_secret = identity_secret;
    this._bot_number = bot_number;
    this._logged = false;
    this._client = new SteamUser();
    this._manager = new TradeOfferManager({
        "steam": this._client, 
        "domain": "xxxxxxx", 
        "language": "en", 
        "pollInterval": "3000",
        "cancelTime": "1800000" 
    })
    this._community = new SteamCommunity();

}

get botNumber() {
    return this._bot_number;
}

get client() {
    return this._client;
}

get manager() {
    return this._manager;
}

set logged(logged) {
    this._logged = logged;
}

login() {
    console.log("In Login Request for Bot: "+this._bot_number)
    this._client.logOn({
        "accountName": this._username,
        "password": this._password,
        "twoFactorCode": SteamTotp.getAuthCode(this._shared_secret)
    })
}

setWebCookies(sessionID,cookies,botNumber,manager) {
    manager.setCookies(cookies, function (err) {
        if (err) {
            console.log(err);
            process.exit(1); // Fatal error since we couldn't get our API key
            return;
        }
        console.log("Got API key: " + manager.apiKey+" for Bot Number: "+botNumber);
    });
    this._community.setCookies(cookies);
}

And here where I use the class and add the Event Handler outside of the class 在这里我使用类并在类外部添加事件处理程序

    bot1.login();

bot1.client.on('webSession', function (sessionID, cookies) {
    bot1.setWebCookies(sessionID,cookies,bot1.botNumber,bot1.manager);
});

bot1.client.on('loggedOn', function () {
    console.log("Bot "+bot1.botNumber+" successfully logged in!");
    bot1.logged(true);
});

And again I would like to have that event handler in the Class itself. 再一次,我想在类本身中拥有该事件处理程序。

setWebCookies() {
  this.client.on('webSession', (sessionID, cookies) => {
      this.setWebCookies(sessionID,cookies,this.botNumber,this.manager);
  });
}

Is there anything wrong with using something like this in your class? 在课堂上使用类似的东西有什么问题吗? Note that I made your callback an arrow function so the this context is retained. 请注意,我已将回调函数设为箭头函数,因此保留了this上下文。 You can also use bind, if you want. 如果需要,还可以使用bind。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM