来自异步召唤的回应不是在Emberjs Helper工作

时间:2015-04-27 17:02:58

标签: jquery ajax asynchronous ember.js rsvp-promise

我正在尝试从ajax调用返回对Ember js助手的响应。在Helper中使用承诺Asynchoronous来电正在返回[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>

1 个答案:

答案 0 :(得分:0)

我不认为你可以从帮助者那里回复承诺。我认为你可以将所有ajax放在路线中,例如在模型函数之后:

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+'">') );
  });
});

}

然后在模板中绑定imgs:

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

当ajax调用完成时,Ember数组将更新,并自动更新模板。