Coffeescript、Facebook JS API 和范围
我正在使用 Coffeescript 并异步加载 Facebook JS api,正如他们在文档中建议的那样。就像这样:
#Load the FB api asynchronously
(->
e = document.createElement("script")
e.async = true
e.src = document.location.protocol + "//connect.facebook.net/en_US/all.js"
document.getElementById("fb-root").appendChild e
)()
doSomething = () ->
# I'd like to call this from the FB context
window.fbAsyncInit = ->
FB.init
appId: fb_app_id
status: true
cookie: true
xfbml: true
oauth: true
# Doesn't work. Is out of scope.
doSomething()
将 Facebook 的内容附加到 window
后,我无法访问 Coffeescript 的匿名包装函数上下文中的内容。
我知道我可以将我的函数定义为 window.doSomething()
,但不确定这是否是最好的方法。
有没有办法让 Facebook 的东西在 Coffeescript 的匿名包装函数的上下文中加载?
I am using Coffeescript and am loading the Facebook JS api asynchronously, as they suggest in their documentation. Like so:
#Load the FB api asynchronously
(->
e = document.createElement("script")
e.async = true
e.src = document.location.protocol + "//connect.facebook.net/en_US/all.js"
document.getElementById("fb-root").appendChild e
)()
doSomething = () ->
# I'd like to call this from the FB context
window.fbAsyncInit = ->
FB.init
appId: fb_app_id
status: true
cookie: true
xfbml: true
oauth: true
# Doesn't work. Is out of scope.
doSomething()
With the Facebook stuff attached to window
, I can't access the stuff in the Coffeescript's anonymous wrapper function context.
I know I could define my function as window.doSomething()
, but am not sure if this is the best way.
Is there a way to have the Facebook stuff load within the context of the Coffeescript's anonymous wrapper function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您认为不应该污染全局名称空间是正确的。继续拥有干净环境的一种方法(明白了:)是使用一个类并将 Facebook 特定功能保留在其中。
这可能会帮助您开始:
祝您好运!
You're right in thinking that you shouldn't pollute the global namespace. One way to continue having a clean environment (get it :) is to use a class and keep your Facebook specific functions in there.
This might help get you started:
Good luck!
这不是范围问题。如果查看编译后的 JS,您会看到在文件顶部声明了 var doSomething 。此外,
doSomething
在window.FBAsyncInit
之前设置为正确的值。That's not a scope issue. If you look at the compiled JS, you'll see
var doSomething
declared at the top of the file. Moreover,doSomething
is set to its proper value beforewindow.FBAsyncInit
.