Search code examples
javascriptfacebookfacebook-graph-apiember.js

Social sharing with ember.js


I have single page app made with ember.js and I have some problems with implementing social sharing.

I need to implement into hbs template something like this:

<a href="http://someaddres.com?u={{model.url}}&title={{model.title}}">Link</a>

However when this is rendered into browser there are additional script tags concatenated within the href string, eventually the link works and I am redirected but instead title I get something like this:

<script id='metamorph-190-start' type='text/x-placeholder'></script>
MyTitle
<script id='metamorph-19... 

Where I need just MyTitle.

More specifically I use the following hbs template for facebook sharing, the model is initialized into the router:

<a href="https://www.facebook.com/login.php?next=http%3A%2F%2Fwww.facebook.com%2Fsharer%2Fsharer.php%3Fs%3D100%26p%255Btitle%255D%3D{{model.title}}%26p%255Burl%255D%3D{{model.url}}%26p%255Bsummary%255D%3D{{model.summary}}%26p%255Bimages%255D%255B0%255D%3D%2540Model.EventImage%2527%253EShare&display=popup"
target="_blank">
<img src="http://www.simplesharebuttons.com/images/somacro/facebook_img.png" alt="Facebook" />
</a>

I also tried third party libraries, like janrain, ShareThis or AddThis, but with them I had initialization problems, buttons were not shown at all when placed into template, and also had problems with messages customization from the model.

Thanks, Igor


Solution

  • Approach 1 - Using unbound

    To get rid of the metamorph tags surrounding your model value, try using the unbound option which does exactly that:

    <a href="http://someaddres.com?u={{unbound model.url}}&title={{unbound model.title}}">Link</a>
    

    Approach 2 - Computing the URL

    In the case you need the model property to be bound and reevaluating when the model changes, then a different approach might be better like for example generating the URL in the controller backing up your template.

    Assuming your controller is e.g. ApplicationController and the links live in the correspondent application template then you could do the following:

    App.ApplicationController = Ember.ObjectController.extend({
      url: function() {
        var url = this.get('model.url');
        var title = this.get('model.title');
        // grab here as many properties you need from your model
        var href = 'http://someaddres.com?u=%@&title=%@'.fmt(url, title);
        return href;
      }.property('model')
    });
    

    And then use the computed url property like this in your template:

    <a {{bind-attr href=url}} target="_blank">Link</a>
    

    Hope it helps.