Search code examples
javascriptember.jsfirebaseember-data

How to pass selected value between routes?


I am quite new to the EmberJS.

This is my model: book.js

import DS from 'ember-data';

export default DS.Model.extend({
    title: DS.attr('string'),
    author: DS.attr('string'),
    picture: DS.attr('string'),
    buyer: DS.attr('string'),
    bought: DS.attr('boolean', { defaultValue: false }),
    createdAt: DS.attr('date', { defaultValue() { return new Date(); } })
});

I have the following route: Books.js

import Ember from 'ember';

export default Ember.Route.extend({
    model: function(){
        return this.store.findAll('book');
    }   
});

and a bit from corresponding books.hbs

{{#each model as |book|}}
        <div class="book-container col-xs-12 col-sm-6 col-md-4">
            <div class="card">
                <div class="wrapper">
                    <div class="details col-md-12">
                        <h3 class="product-title">Title {{book.title}}</h3>
                        <p class="product-description">Author:{{book.author}}</p>
                        {{#link-to 'books.give' }} Buy {{/link-to}}
                    </div>
                </div>
            </div>
        </div>
{{/each}}

This code returns all the books that I currently store in the app.

The idea is to get selected Book object from books.hbs and display it in give.hbs.

I wanted to use this line

{{#link-to 'books.give' }} Buy {{/link-to}}

to pass single a single book from books.hbs to give.hbs, but I don't know how to do that and if its the way to go..

In gift.hbs I partially invented a very inefficient way of doing it by looping all the books again and if the title is a match then display it...

  {{#each model as |book|}}
    {{#if (eq book.title "Harry Potter")}}
      <h2><b>{{book.title}}</b></h2>
    {{/if}}
  {{/each}}

Obviously the "Harry Potter" string is hard-coded but it could have been passed from books.hbs and that would do the trick since my data is relatively small.


Solution

  • It depends on how do you want to represent URL.
    if it's books/give/bookId => then go for dynamic segments
    if its books/give?bookId=1 => then go for query params implementation

    Inside books.give route get the particular book record using findRecord and use it.