jwcrpq
Last Updated: February 25, 2016
·
2.466K
· shavit
Ac5c8c4c9580e06cb7dfef8405cbce34

Facebook Javascript SDK with CoffeeScript

Introduction

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 = ->
  FB.init
    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.Canvas.setAutoGrow()
  FB.getLoginStatus((data) ->
    if (data.status == "connected")
      uid = data.authResponse.userID
      accessToken = data.authResponse.accessToken;
      FB.api("/me", (data) ->
        console.log("Hello #{data.name}")
      )
    else
      if (response.status == "not_authorized")
      # the user is logged in to Facebook,
      # but has not authenticated your app
      else
      # the user isn't logged in to Facebook.
    )

PageScript = document.getElementsByTagName("script")[0]
return if document.getElementById("FBScript")
FBScript = document.createElement("script")
FBScript.id = "FBScript"
FBScript.async = true
FBScript.src = "//connect.facebook.net/en_US/all.js"
PageScript.parentNode.insertBefore(FBScript, PageScript)

Gist for this code:

https://gist.github.com/shavit/5055943

http://conpanna.net

Say Thanks
Respond