2017-02-18 9 views
0

가 여기 내 단순화 된 상황입니다 : 내 제품 템플릿에서hasMany 관계에서 하나의 레코드를 검색하기위한 Ember 계산 속성?

// model/price-source.js 

export default DS.Model.extend({ 
    price: DS.attr('number'), 
    product: DS.belongsTo('product') 
)}; 

// model/product.js 

export default DS.Model.extend({ 
    priceSources: DS.hasMany('price-source') 
)}; 

, 단순히과 같이, 가장 낮은 가격으로 소스를 참조 할 수 있도록하려면 :

// templates/products.hbs 

{{#each model as |product|}} 
<span>{{product.cheapestSource.price}} €</span> 
{{/each}} 

가 어떻게 갈 것 cheapestSource 계산 된 속성을 설정하는 방법에 대해? 나는 이런 식으로 뭔가해야 할 것 상상 : 문제는

// model/product.js 

    cheapestSource: Ember.computed('priceSources', function() { 
    let sources = this.get('priceSources'); 
    let cheapest = sources.get('firstObject'); 

    // iterate over sources and set cheapest to whichever has the lowest price 

    return cheapest; 
    }) 

, 나는 조금 생각이 어떻게 (떨어져 핸들 {{#each}} 헬퍼를 사용)를 hasMany의 관계를 통해 루프 및 계산 된 속성이 다른 모델의 단일 Ember Data 레코드로 구성 될 수 있는지 여부. 근원지가 @ 어떻게 든 그걸 어떻게 다루는가?

도움과 아이디어 감사합니다.

답변

0

priceSources를 계산 된 속성 인 sortedPrices로 정렬 한 다음 템플릿에서 sortedPrices의 firstObject를 호출하면됩니다. 곧 실제 해결책으로이 게시물을 편집 할 것입니다.

핸들 막대 블록을 주석으로 처리하면 HTML 내부의 렌더링이 중단된다는 것을 인식하지 못하기 때문에 테스트하는 데 오래 걸렸습니다. ... 자기에


편집을 참고 :이 그것을했다 :

export default DS.Model.extend({ 
    priceSources: DS.hasMany('price-source'), 
    sortProperties: ['price:asc'], 
    sortedSources: Ember.computed.sort('priceSources', 'sortProperties') 
}); 

를 다음 템플릿에서 :

<span>{{product.sortedSources.firstObject.price}} €</span> 

작품 확인을, 코드 톤없이.

0

가장 저렴한 소스를 사용해야하는 컨트롤러에서 수행 할 수 있습니다.

cheapestSource: Ember.computed('priceSources', function() { 
     let sources = this.get('priceSources'); 
     let cheapest = sources.get('firstObject'); 
     let array = sources.mapBy("price"); 
     let min = array.reduce(function(a, b, i, array) {return Math.min(a,b)}); 
     sources.forEach(function(source){ 
      if (source.get("price") == min){ 
      cheapest = source; 
      } 
     }); 
    return cheapest; 
    }) 

모델은 원하는대로 달성하기가 어렵습니다. 계산 된 하나를 사용하고 템플릿이 렌더링 된 후 계산 된 개체가 필요한 개체가되는 이유입니다.

cheapestSource: Ember.computed('priceSources', function() { 
     let product = this; 
     this.get('priceSources').then((sources)=>{ 
     let array = sources.mapBy("price"); 
     if(array.length>0){ 
     let min = array.reduce(function(a, b, i, array) {return Math.min(a,b)}); 
     sources.forEach(function(source){ 
      if (source.get("price") == min){ 
      product.set("cheapestSource", source); 
      } 
     }); 
     } 
    }); 
    }) 

난 그냥 추가 엠버의 제품 모델에 다음 레일에 활성 모델 어댑터를 사용하여 내 사용자 지정 시리얼에 제품의 일부 예를 cheapestSourcePrice에 대한 보답으로이 같은 문제가있을 때 cheapestSourcePrice 및 템플릿 {{product.cheapestSourcePrice} } 너는 t want ember to do heavy lifting like this but if you don을 제어하고 서버를 제어한다. 그리고 소스 코드를 값싼 소스로 설정 한 후 한 가지 더 계산 된 소스는 새로 고침 할 때까지 더 이상 계산되지 않습니다. 당신은 당신이 다음 모델에 하나 개 이상의 속성을 추가로 설정해야합니다 계산 유지해야하는 경우 그

예를

을 insted cheapestSource2 : DS.attr()

이 객체

제품으로이 허용됩니다. set ("cheapestSource2", source);

다음 템플릿 에서

{{product.cheapestSource}} {{product.cheapestSource2.price}} 당신이 전화를 먼저 속성을 호출이 너무 계산

.

+0

나는 (https://guides.emberjs.com/v2.11.0/models/relationships/#toc_relationships-as-promises) 가이드 [약속으로 관계]이 글을 읽고 있어요. 우리가하고있는 것처럼 직접 접근 할 수 있습니까? 가능한 한 내 대답을 설명하십시오. 그리고 또한 종속 키'priceSources. @ each.price'가 유용 할 수도 있습니다. – kumkanillam

+0

컨트롤러에서이 작업을 수행 했으므로이 질문을하는 이유를 확인하기 위해 모델 thx에서이 작업을 수행했습니다. –

+0

@ Sedad.Kosovac 불행히도 priceource 객체가 표시되지 않습니다 (Ember Inspector에서). 나는 오류가 발생하지 않습니다. 'return this.get ('priceSources.firstObject')'를 시도해 보았습니다. 어쨌든 소스 정렬이 필요할 것이므로 가장 저렴한 소스를 얻는 가장 좋은 방법은 먼저 정렬 한 다음 sortedSources 계산 된 속성에서 firstObject를 검색하는 것입니다. –

0

시간이 있다면이 솔루션을 사용해보십시오. this.get('priceSources') Promise를 반환하므로 결과에 액세스 한 다음 DS.PromiseObject로 래핑하면 템플릿의 일반 개체처럼 액세스 할 수 있습니다.

cheapestSource: Ember.computed('[email protected]', function() { 
     return DS.PromiseObject.create({ 
      promise: this.get('priceSources').then(sources => { 
       let resultObj = {} 
        //sources is normal array you can apply your logic and set resultObj 
       return resultObj; 
      }) 
     }); 
    }) 
+0

구성 요소 (또는 컨트롤러) 또는 모델에 들어가야합니까? 모델에서 시도했는데, 'Uncaught TypeError : this.get (...). then then not a function'입니다. 소스 코드를 정렬 한 후 계산 된 속성 값을 가장 저렴하게하고 싶다면 좋은 해결책이라고 생각합니다. 예를 들어' sources =>'함수를 사용하면 sources.firstObject, sources.get ('firstObject'), sources [0] 또는 그 밖의 올바른 구문을 반환 할 수 있습니다. –

+0

모델 및 기본값으로 priceSources : DS를 정의 할 수 있습니다. hasMany ('price-source', {async : true})'. async 속성이 true이면 Promise를 반환하므로 'then'은 문제이고 false이면 DS.ManyArray를 반환하므로'then'은 문제가되지 않습니다. 그 오류가 발생합니다. 내가 어떤 예를 해결할 수 있습니다. 그냥이 심한 throguh이 [점화기 기사로드 중] (ht tps : //emberigniter.com/guide-promises-computed-properties/) @VilleLehtinen – kumkanillam