我想知道如何在Ecma6类中添加Eventhandler。以下示例有效,但我想在类本身中使用事件处理程序。
这里是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);
}
在这里我使用该类并在类之外添加事件处理程序
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);
});
我希望在Class本身中拥有该事件处理程序。
答案 0 :(得分:0)
setWebCookies() {
this.client.on('webSession', (sessionID, cookies) => {
this.setWebCookies(sessionID,cookies,this.botNumber,this.manager);
});
}
在课堂上使用这样的东西有什么问题吗?请注意,我使您的回调成为箭头函数,因此保留了this
上下文。如果需要,也可以使用bind。