3

I'm trying to implement 2 Share buttons. The Facebook Like Button and the Twitter Share Button.

But i'm having a problem with turbolinks.. After looking it up i found an interesting article.

The solution stated that by removing the initial script from the application.html.erb and including the below file will fix the problem.

fb_root = null
fb_events_bound = false

$ ->
  loadFacebookSDK()
  bindFacebookEvents() unless fb_events_bound

bindFacebookEvents = ->
  $(document)
    .on('page:fetch', saveFacebookRoot)
    .on('page:change', restoreFacebookRoot)
    .on('page:load', ->
      FB?.XFBML.parse()
    )
  fb_events_bound = true

saveFacebookRoot = ->
  fb_root = $('#fb-root').detach()

restoreFacebookRoot = ->
  if $('#fb-root').length > 0
    $('#fb-root').replaceWith fb_root
  else
    $('body').append fb_root

loadFacebookSDK = ->
  window.fbAsyncInit = initializeFacebookSDK
  $.getScript("//connect.facebook.net/en_US/all.js#xfbml=1")

initializeFacebookSDK = ->
  FB.init
    appId     : 'YOUR_APP_ID'
    channelUrl: '//WWW.YOUR_DOMAIN.COM/channel.html'
    status    : true
    cookie    : true
    xfbml     : true

The Same goes for the Twitter Problem:

twttr_events_bound = false

$ ->
  bindTwitterEventHandlers() unless twttr_events_bound

bindTwitterEventHandlers = ->
  $(document).on 'page:load', renderTweetButtons
  twttr_events_bound = true

renderTweetButtons = ->
  $('.twitter-share-button').each ->
    button = $(this)
    button.attr('data-url', document.location.href) unless button.data('url')?
    button.attr('data-text', document.title) unless button.data('text')?  
  twttr.widgets.load()

I done that, but for some reason my problem isn't going away.. Could someone help me get this right ?

Mini John
  • 7,855
  • 9
  • 59
  • 108

1 Answers1

0

Refer to this question Rails 4: how to use $(document).ready() with turbo-links (the answer with the most votes), so try:

ready = ->

  ...your coffeescript goes here...

$(document).ready(ready)
$(document).on('page:load', ready)

I got an issues before with turbolink, while I load fb script in the homepage, and follow the link to another page, and the fb script doesn't reload. So I try to add data-turbolink-track = false and it worked. Hope this help.

Community
  • 1
  • 1
duykhoa
  • 2,227
  • 1
  • 25
  • 43