Ember Facebook Components

16 Dec 2014

Getting Facebook integrated into an existing website may sound daunting but using the Facebook UI API and Ember together was entirely too easy.

Ember-CLI has a directory called initializers that are loaded at app start up. This proves useful for things such as Google Analytics or Facebook SDK initialization.

Here is what my facebook-sdk.js initializer looks like. Note the use of global FB. This is used so that JSHint doesn’t freak out when building the project.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* global FB */
export default {
  name: 'facebook',

  initialize: function() {
    var fbAsyncInit = function() {
      FB.init({
        appId      : '<your app id>',
        xfbml      : true,
        version    : 'v2.2'
      });
    };

    (function(d, s, id){
       var js, fjs = d.getElementsByTagName(s)[0];
       if (d.getElementById(id)) {return;}
       js = d.createElement(s); js.id = id;
       js.src = "//connect.facebook.net/en_US/sdk.js";
       fjs.parentNode.insertBefore(js, fjs);
     }(document, 'script', 'facebook-jssdk'));

    window.fbAsyncInit = fbAsyncInit;
  }
};

Now I can use the global FB.ui in components with ease. So far I’ve only integrated the Facebook Send Dialogue into the application, but this alone can show how easy it is for the Facebook SDK to now integrate with your Ember Application.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* global FB */
import Ember from 'ember';

export default Ember.Component.extend({
  classNames: ['facebook-send'],

  actions: {
    sendLink: function() {
      FB.ui({
        method: 'send',
        link: 'http://imgur.com',
      });
    }
  }
});

Check out what other pieces you could use in your Ember application by visiting the Facebook JS SDK Documentation

I need the url sent in the FB send dialogue to be relative to the environment I am in so I added a little mixin I can use throughout the site to generate proper links for each environment. Check it out!

1
2
3
4
5
6
7
8
import Ember from 'ember';

export default Ember.Mixin.create({
  currentBaseUrl: function() {
    var pathArray = window.location.href.split( '/' );
    return '%@//%@'.fmt(pathArray[0], pathArray[2]);
  }.property()
});
Update: I expand on this post in a talk I gave for a SanDiego.js and San Diego Ember talk in February 2015. Watch it here or view the slides here
comments powered by Disqus