麻烦模型和计算属性的麻烦

时间:2018-02-15 21:52:27

标签: ember.js

我有一个书模型,我使用mapBy()计算属性来检索模型中的所有价格。 allPrices: mapBy('books', 'price');  然后我使用max()来获得最高价值。 maxPrice: max('allPrices');该部分按预期工作。  我的问题是,我想显示最高价格和与该价格相关的书的标题,但我无法弄清楚如何做到这一点。

<h2>Max book price: {{format-currency maxPrice}} </h2>
<h2>Which belongs to the book {{book.title}} </h2>

如何实现这一目标?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

所以有几件事:

你需要的是这本书本身的最高价格。 为了得到这个,只需按价格降序排序并获得第一个。

执行此操作后,您的模板将变为:

<h2>Max book price: {{format-currency bookWithMaximumPrice.price}} </h2>
<h2>Which belongs to the book {{bookWithMaximumPrice.title}} </h2>

这样做的javascript方式如下:

bookWithMaximumPrice: computed('books.@each.price', function() {
  let books = this.get('books');
  let booksSortedByPrice = books.toArray().sort(function(bookA, bookB) {
    return bookB.get('price') - bookA.get('price');
  });
  return booksSortedByPrice.get('firstObject');
});

更Emberish方式是使用计算宏首先按价格排序,然后获得第一个:

sortProperties: ['price:desc'],
booksSortedByPrice: computed.sort('books', 'sortProperties'),
bookWithMaximumPrice: computed.readOnly('booksSortedByPrice.firstObject')

答案 1 :(得分:0)

使用sort computed property -

sortProperties: ['price'],
sortedBooks: sort('books', 'sortProperties'),
highestPricedBook: alias('sortedBooks.lastObject')

{{highestPricedBook.price}}
{{highestPricedBook.name}}
相关问题