ember.js - ember.js - Trouble with ember model and computed properties - answerstu - answerstu.com answerstu

ember.js - Trouble with ember model and computed properties

I have a book model that i use a mapBy() computed property on to retrieve all the prices in the model. allPrices: mapBy('books', 'price'); Then i use max() to get the highest value. maxPrice: max('allPrices'); That part works as expected. The problem i have is that i want to display the max price AND the title of the book associated with that price but i cant figure out how to do it.

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

How can this be achieved? Any help would be appreciated.

2 Answers

  1. Abel- Reply


    So a couple of things:

    What you need is the book itself with the maximum price. In order to get that just sort the books by price descending and get the first one.

    Once you do this, your template becomes:

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

    A javascript way of doing this is as follows:

    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');

    A more Emberish way is to use computed macros to first sort by price and then to get the first one:

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


    Use sort computed property -

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>