Last Updated: February 25, 2016
· shavit

Facebook Javascript SDK with CoffeeScript


This is a better and cleaner approach, for using the Facebook Javascript SDK:

  1. Javascript code is separated from the markup.
  2. The code is re-usable

How To Use

  1. Add environment variables
  2. Layout
  3. CoffeeScript

1: Environment Variables

If you are using forman, the variables will be loaded from the .env file.
Notice: Remove the .env file from production in the .gitignore file.
echo FACEBOOK_APP_ID=1234 >> .env echo FACEBOOK_APP_SECRET=1234 >> .env

2: Layout

Add the environment variables into the application layout, as a data attributes.

With Jinja:
<div id="fb-root" data-app-id="{{ ENV['FACEBOOK_APP_ID'] }}"></div>

With Liquid:
<div id="fb-root" data-app-id="{{ ENV['FACEBOOK_APP_ID'] }}"></div>

With ERB:
<div id="fb-root" data-app-id="<%= ENV['FACEBOOK_APP_ID'] %>"></div>

With Jade:
div(id="fb-root", data-app-id= ENV['FACEBOOK_APP_ID'])

With HAML:
div{id="fb-root", data-app-id=ENV['FACEBOOK_APP_ID']}

Or in HTML
<div id="fb-root" data-app-id="1234"></div>

3. CoffeeScript

Notice: You can use channel.html file, instead of loading directly the Facebook JS files.

# You should add the Facebook App ID and the channel url (optional), in the #fb-root element, as a data- attribute:
#   <div id="fb-root" data-app-id="<%= ENV['FACEBOOK_APP_ID'] %>" data-channel-url="<%= url_no_scheme('/channel.html') %>"></div>
window.fbAsyncInit = ->
    appId: document.getElementById("fb-root").getAttribute("data-app-id")
    channelUrl: document.getElementById("fb-root").getAttribute("data-channel-url")
    status: true,
    cookie: true,
    xfbml: true

  FB.Event.subscribe('auth.login', (response) ->
    window.location = window.location
  FB.getLoginStatus((data) ->
    if (data.status == "connected")
      uid = data.authResponse.userID
      accessToken = data.authResponse.accessToken;
      FB.api("/me", (data) ->
        console.log("Hello #{}")
      if (response.status == "not_authorized")
      # the user is logged in to Facebook,
      # but has not authenticated your app
      # the user isn't logged in to Facebook.

PageScript = document.getElementsByTagName("script")[0]
return if document.getElementById("FBScript")
FBScript = document.createElement("script") = "FBScript"
FBScript.async = true
FBScript.src = "//"
PageScript.parentNode.insertBefore(FBScript, PageScript)

Gist for this code:

Have a fresh tip? Share with Coderwall community!

Post a tip