2014-06-24 17 views
0

想象一个呈现HTML表格的组件。表中的数据来自远程JSON。Ember afterRender组件/非异步AJAX

该组件的另一部分依赖于完全呈现的HTML表(使用JSON数据)。

在组件的init事件中,我检索JSON并设置组件将用于呈现表的数据。

我不能使用afterRender钩子来进一步处理表,因为当触发afterRender时,表存在但没有JSON数据。

我注意到组件外部的一个afterRender钩子工作(表格完全呈现),但是我通过运行属于组件内部的代码来破坏封装。

我可能会同步获得JSON,或者是承诺内的承诺?我将如何做后者?我的意思是在组件的init挂钩上,我如何创建一个只有在它内部的promise被返回时才会返回的promise?

或者我该如何处理这种灰烬方式?

回答

0

你绝对可以将你的承诺连锁在地狱之外。

var items = []; 

this.set('items', items); 

$.getJSON('/colors').then(function(results){ 
    results.forEach(function(item){ 
    item.color +=" is pretty"; 
    }); 
    return results; 
}).then(function(prettyResults){ 
    prettyResults.forEach(function(item){ 
    items.pushObject(item); 
    }); 
}); 

http://emberjs.jsbin.com/OxIDiVU/724/edit

超深费解的承诺

new Ember.RSVP.Promise(function(resolve){ 
    resolve($.getJSON('/colors')); 
}).then(function(results){ // this isn't hit til the json is returned 
    results.forEach(function(item){ 
    item.color +=" is pretty"; 
    }); 
    return new Ember.RSVP.Promise(function(resolve){ 
    Ember.run.later(function(){ 
     resolve(results); 
    }, 4000); 
    }); 

}).then(function(prettyResults){ // this isn't hit til the 4 second resolve is done 
    prettyResults.forEach(function(item){ 
    items.pushObject(item); 
    }); 
}); 

http://emberjs.jsbin.com/OxIDiVU/725/edit

+1

有道理,谢谢你教我的东西,我将需要:)不过,我想我只是发现这是一个更好的方法。如果我“观察”HTML表所依赖的属性,那么在观察者的表内完全呈现,所以我可以做我需要的东西!甜。 – Ivan

+0

伊万倾听模型的状态成为加载是做的方式(DS.Model#isLoaded),请考虑回答你自己的问题。另请看这篇文章http://blog.trackets.com/2013/01/27/ember-data-in-depth.html。 –