0

我正在尝试将来自 ajax 调用的响应返回给 Ember js 助手。在 Helper 中使用PromiseAsynchoronous调用正在返回。[object Object]

console.log(data.thumbnail_url);正在工作,但回调没有返回 ( <img...>) 响应。这是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);
 });

这是 HandleBars 模板:

<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>
4

1 回答 1

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.

于 2015-04-27T19:41:04.270 回答