0

I'm trying to return a response from an ajax call to the Ember js helper. An Asynchoronous call using Promise in Helper is returning [object Object].

console.log(data.thumbnail_url); is working but the callback is not returning the (<img...>)response. Here is JsFiddle.

App.IndexRoute = Ember.Route.extend({
  model: function() {
   // for simply showing the problem, I've put the instagram id
   // Actually I will parse the id from the post body
   return ['fA9uwTtkSN'];
  }
});

Ember.Handlebars.registerBoundHelper("format-inst", function(input){
 // Add this part
 if (typeof input == 'undefined'){return;}

 function foo (URL) {
   return $.ajax({
       url: URL,
       dataType: "jsonp"
  });
 }
     var URL = 'http://api.instagram.com/oembed?url=http://instagr.am/p/'+input;
     var r = foo(URL).done(function (data){
                console.log(data.thumbnail_url);
                return '<img src="'+data.thumbnail_url+'">';                        
     });
     return new Ember.Handlebars.SafeString(r);
 });

Here is the HandleBars Template:

<script type="text/x-handlebars">
<h2>Welcome to Ember.js</h2>

 {{outlet}}
</script>

<script type="text/x-handlebars" data-template-name="index">
 <ul>
 {{#each post in model}}
  <li>{{format-inst post}}</li>
 {{/each}}
 </ul>
</script>
Hasib Mahmud
  • 806
  • 1
  • 10
  • 29

1 Answers1

0

I don't think you can return a promise from a helper. I think you could put all the ajax in the route, for example after the model function:

setupController: function(controller, model){
var imgs = Ember.A([]);
controller.set('imgs', imgs );

model.forEach( function(imgId){
  var url = 'http://api.instagram.com/oembed?url=http://instagr.am/p/'+imgId;
  $.ajax({url: URL, dataType: "jsonp"}).done(function(data){
    imgs.pushObject(Ember.Handlebars.SafeString('<img src="'+data.thumbnail_url+'">') );
  });
});

}

Then in the template just bind on imgs:

{{#each image in imgs}}
  <li>{{image}}</li>
{{/each}}

As the ajax calls complete, the Ember Array will get updated, and automatically update the template.

Tony
  • 388
  • 3
  • 11
  • Thanks, But I guess you didn't notice the comment in the code. That is, these are not separate images. There're inside the post body and I want to show them like that not as separated. – Hasib Mahmud Apr 28 '15 at 03:25