尝试使用MeteorJS瓦特/ twit节点模块,错误:]
所以我使用MeteorJS和twit Node模块来访问tweet的屏幕名称。 仍然只是testing代码,看看我是否可以从twitter中检索JSON。
这是我的代码:
var Tget = Meteor.wrapAsync(T.get); Meteor.methods({ 'screenName' : function() { try { var result = Tget('search/tweets', {q:'#UCLA',count:1}); JSON.stringify(result); console.log(result); } catch (e) { console.log(e); return false; } } })
我收到的错误是:
[TypeError: Object #<Object> has no method 'request']
这里是twit模块git: https : //github.com/ttezel/twit/blob/master/README.md
我想我明白。 这里是T.get
的代码 :
Twitter.prototype.get = function (path, params, callback) { return this.request('GET', path, params, callback) }
正如你所看到的,它期望this
有方法request
。 但是,因为我们使用wrapAsync
而不关心执行上下文( 用this
访问 ),所以失败了。
考虑一下这个例子(你可以在浏览器控制台中复制/粘贴):
var obj = { foo : 'foo', logThis : function() { console.log(this); } };
如果我们执行obj.logThis()
我们有: Object { foo: "foo", logThis: obj.logThis() }
但是,如果我们做了以下…
var otherLogThis = obj.logThis; otherLogThis();
它会loggingWindow
对象,因为我们从上下文中获取了该函数!
如何解决这个问题? 绑定函数? 棘手的电话?
不,meteor有解决scheme。 wrapAsync
可以有两个参数 …第二个是上下文!
var Tget = Meteor.wrapAsync(T.get, T);
如果你想了解更多关于JavaScript的情况,我build议这本书:
https://github.com/getify/You-Dont-Know-JS/
它是自由和开源的,除了我最深刻的感情和温柔的回忆,除了感受到我的大脑在各种有趣的方式上长大时,我都没有任何附属关系。