简体   繁体   English

将本机数组/对象转换为Ember.Array / Ember.Object的最佳实践

[英]Best practise to transform native array/object into Ember.Array/Ember.Object

I have an ember component expecting a parameter as an array of objects. 我有一个余烬组件,期望参数作为对象数组。 By default, this parameter is gonna be a native array with native objects inside. 默认情况下,此参数将是内部包含本机对象的本机数组。 I'd like to transform this array into an ember array containing ember objects. 我想将此数组转换为包含ember对象的ember数组。

I was thinking about something like that, but this will create an infinite loop firing the observer every time: 我正在考虑类似的事情,但这会创建一个无限循环,每次触发观察者:

export default Ember.Component.extend({
   content: null,

   contentDidChange: function () {
        var content = Ember.A();
        this.get('content').forEach(function (item) {
            content.addObject((item.constructor.toString() !== 'Ember.Object') ? Ember.Object.create(item) : item);
        });
        this.set('content', content);
    }.observes('content'),
});

What is the best practise to do that? 最佳做法是什么?

Thanks 谢谢

You can just modify the initial parameter when the component first boots up on didInsertElement like so: 您可以在组件首次在didInsertElement上启动时修改初始参数, didInsertElement所示:

App.ArrContentComponent = Ember.Component.extend({
  content: null, 

  modifyContent: function(){
    var content = this.get('content').map(function(item){
      return Ember.Object.create({ name: item });
    });

    this.set('content', content);
  }.on('didInsertElement')
});

Working example here 这里的工作示例

If the reason why you need Objects inside your component is because you are doing this.get(.. then you can get around by using Ember.get(.. instead. 如果在组件内部需要对象的原因是因为您正在执行this.get(..则可以改用Ember.get(..

If thats not the case, then I would recommend binding your component to a transformed property, and not the original content . 如果不是这种情况,那么我建议将您的组件绑定到转换后的属性,而不是原始content

transformedContent: null,
makeItem: function(item) { 
  return Ember.Object.create(item);
}),
cloneItems: function() { 
  this.set('transformedContent', this.get('content').map(this.makeItem));
}.observes('content'),

If you want best practice , then I would create a computed array , that transforms the items as they come and go, which you will be able to re use. 如果您想要最佳实践 ,那么我将创建一个计算数组 ,该数组可以随着项目的来回进行转换,您将可以重复使用它们。

transformedContent: App.computed.objectArray('content')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM