[英]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.