[英]CoffeeScript function as parameter in node.js API
我正在CoffeeScript中為Atom編寫插件,並且正在使用此nodejs API(telegram.link) 。 它具有一些不對稱的函數,因此我必須將函數作為參數傳遞,稱為回調。 我的問題是,當我使用以下代碼時:
login: ->
console.log 'Loging in'
@client = telegramLink.createClient({
id: config.telegram.prod.app.id,
hash: config.telegram.prod.app.hash,
version: '0.0.1',
lang: 'en'
},
config.telegram.prod.primaryDataCenter);
@client.createAuthKey(@authCallback)
console.log @client
authCallback: (auth) ->
console.log auth
@client.auth.sendCode(config.telegram.test.telNr, 5, 'en', @sendCodeCallback)
編譯為:
login: function() {
console.log('Loging in');
this.client = telegramLink.createClient({
id: 12345,
hash: 'q1w2e3r4t5y6u7i8o9p0',
version: '0.0.1',
lang: 'en'
}, config.telegram.prod.primaryDataCenter);
this.client.createAuthKey(this.authCallback);
return console.log(this.client);
},
authCallback: function(auth) {
console.log(auth);
return this.client.auth.sendCode(config.telegram.test.telNr, 5, 'en', this.sendCodeCallback);
}
@client
在authCallback函數中未定義。
我讀了Stackoverflow( CoffeeScripts類-訪問callback中的屬性 ),我應該使用=>
(fat-arrow),所以我嘗試了以下操作,生成了以下編譯腳本:
authCallback: (function(_this) {
return function(auth) {
console.log(auth);
return _this.client.auth.sendCode(config.telegram.test.telNr, 5, 'en', _this.sendCodeCallback);
};
})(this)
但是@client
仍未定義。 我認為也許從API調用的回調函數不再正常工作。
我還能做些什么來保持原始范圍,但使其與API一起使用?
當我查看代碼的含義時,我會猜測您不在類之內。 如果您不在類的實例中,則“ this”或“ @”將不起作用。 第二件事是回調的定義。 不應將其定義為您的類的方法。 該類可能看起來像這樣:
class MyClass
constructor: ->
// do something
login: ->
@client = telegramLink.createClient({
id: config.telegram.prod.app.id,
hash: config.telegram.prod.app.hash,
version: '0.0.1',
lang: 'en'
@client.authCallback: (auth) =>
console.log auth
@client.auth.sendCode(config.telegram.test.telNr, 5, 'en', @sendCodeCallback)
要使您的類工作正常,您需要創建一個實例,所以也許這不是您想要的。
您可以更改其功能,就像僅通過函數定義它一樣。
login: ->
console.log 'Loging in'
client = telegramLink.createClient({
id: config.telegram.prod.app.id,
hash: config.telegram.prod.app.hash,
version: '0.0.1',
lang: 'en'
},
config.telegram.prod.primaryDataCenter);
client.createAuthKey(@authCallback)
console.log @client
authCallback: (auth) ->
console.log auth
client.auth.sendCode(config.telegram.test.telNr, 5, 'en', sendCodeCallback)
提示:createClient方法中選項字典的定義看起來像JS,而不像Coffescript。 也是“;” 你不應該使用。 混淆定義也可能會導致一些錯誤。
今天,我找到了解決問題的方法。 現在我的代碼如下所示:
login: ->
console.log 'Logging in'
@client =
telegramLink.createClient({
id: config.telegram.prod.app.id
hash: config.telegram.prod.app.hash
version: '0.0.1'
lang: 'en'
}
config.telegram.prod.primaryDataCenter)
@client.createAuthKey((auth) =>
console.log @client.auth
@client.auth.sendCode(
config.telegram.test.telNr,
5,
'en',
@sendCodeCallback))
console.log @client
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.