Skip to content

Instantly share code, notes, and snippets.

@benjasHu
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save benjasHu/8147bf296d2166888f5f to your computer and use it in GitHub Desktop.

Select an option

Save benjasHu/8147bf296d2166888f5f to your computer and use it in GitHub Desktop.
Facebook Share in a RequireJS Module (with callbacks)
define([
'jquery',
'domReady',
'path/to/facebook'
],
function( $, domReady, Facebook ) {
"use strict";
var app = {
init: function() {
domReady(function() {
/* FACEBOOK
-------------------------------------------------*/
Facebook.init({
appId: 'your-app-id'
});
$('.facebook-share-btn').on('click', function( e ) {
e.preventDefault();
Facebook.share({
method: 'share',
href: 'you-url-to-share'
}, function( response ) {
console.log(response);
});
});
Facebook.events
.on('fb-share.success', function( e ) {
console.log('success facebook share');
})
.on('fb-share.error', function( e ) {
console.error('error facebook share');
});
});
}
};
/* INIT
------------------------------------------------------------------------------------*/
return app;
});
(function( require ) {
"use strict";
/* REQUIRE CONFIG
--------------------------------------------------*/
require.config({
paths: {
domReady: 'path/to/domReady',
jquery: 'path/to/jquery',
facebook: '//connect.facebook.net/es_ES/all'
},
shim: {
facebook : { exports: 'FB' }
}
});
})( require );
define([
'jquery',
'facebook'
],
function ( $ ) {
'use strict';
var app = {
events: $({}),
init: function( data ) {
var options = $.extend(true, {
appId : '',
status : true,
xfbml : true,
version: 'v2.1'
}, data);
FB.init(options);
},
share: function( data, callback ) {
var options = $.extend(true, {
method : 'share',
href : window.location.href.replace('#', '')
}, data),
status = '';
FB.ui(options, function(response){
if (response && !response.error_code) {
status = 'success';
app.events.trigger('fb-share.success');
} else {
status = 'error';
app.events.trigger('fb-share.error');
}
if(callback && typeof callback === "function") {
callback.call(this, status);
} else {
return response;
}
});
}
};
/* INIT
------------------------------------------------------------------------------------*/
return app;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment