Friday, November 30, 2012

A knockout binding handler to update dynamically loaded Facebook plugins

When you are loading Facebook social plugins, Facebook takes the values, such as for the "data-href" value for a comments box, when the page is initially created.

Sometimes, you want to update the plugin after an observable has been updated or based on dynamic values coming in from a knockout template.

Here is a simple knockout binding handler that will call FB.XFBML.parse() to update the page after an element is bound.


ko.bindingHandlers.updateFacebook = {     
    init: function (element) {
        FB.XFBML.parse();
    }
};

And you can can use it like this, overwriting the initial value with the attr value:


<div class="fb-comments" data-bind="attr: { 'data-href': viewModelUrl  }, updateFacebook: true" data-href="@Request.Url" data-num-posts="10" data-width="400">
</div>

The FB.XFBML.parse() method will allow you update either the whole page or an element by id, so you could also do:


ko.bindingHandlers.updateFacebook = {     
    init: function (element) {
         var id = $(element).attr('id');
         FB.XFBML.parse( document.getElementById(id) );
    }
};

This is put together from Facebook's parse function, Ryan Niemeyer and from this post

No comments:

Post a Comment