Search code examples
javascriptember.jsember-components

Sending an action from a sub component to parent component in Ember 2.2


Hi I'm trying to send an action from a sub component back up to the parent component so it can access this.store and perform a DB action. The basic layout is this:

app/templates/item/index.hbs -> does a loop of items using component

            {{#each model as |item|}}
                {{item-listing item=item}}
            {{/each}}

app/templates/components/item-listing.hbs

<li><a {{action 'copyItem' item}}>Copy</a></li>

In app/components/item-listing.js I have to define an action or I get an action not defined error. From here this.store is undefined, so I'm trying to bubble the action up.

actions: {
    copyItem: function(item) {
        this.sendAction('copyItem', item);
    },

From here I'm lost. I've tried putting actions on all of the following:

/app/routes/item/index.js /app/routes/item.js

But it never seems to get past the sendAction call. What am I doing wrong?


Solution

  • You have to:

    1. Define that action (copyItem) in your controller (ItemIndexController).
    2. Pass that action in template loop:

    1st way:

    {{#each model as |item|}}
        {{item-listing item=item copyItem='copyItem'}}
    {{/each}}
    

    2nd way:

    {{#each model as |item|}}
        {{item-listing item=item copyItem=(action 'copyItem')}}
    {{/each}}