【发布时间】:2015-11-10 18:02:41
【问题描述】:
我正在用 CoffeeScript 为 Atom 编写一个插件,我正在使用 this 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 classes - access to property in 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 一起工作?
【问题讨论】:
-
authCallback是如何被调用的?请记住,(Java|Coffee)Script 函数中的this取决于函数的调用方式,而不是定义的方式或位置(当然绑定函数除外)。使用=>应该可以解决问题。你看过@在authCallback里面是什么吗?你确定你先打电话给login吗?你确定你在同一个对象上调用login和authCallback? -
@muistooshort 来自 API 的源代码
if (callback) { this.client.once('sendCode', callback); }。 API 是用纯 nodejs 而不是 CoffeeScript 编写的,所以根本没有@。是的,我确定我首先调用了登录,因为它是由 Atom 中的菜单按钮触发的。如果您想查看我的整个项目代码,我已在 Github 上分享了它 -
@是 CoffeeScript 对this的简写,所以@就在那里。我不知道this.client.once('sendCode', callback)做了什么,所以你必须深入挖掘。或者你可以在authCallback中console.log(@)自己看看。 -
请回答问题,而不是问题的一部分:)
标签: javascript node.js coffeescript atom-editor