user1224298
user1224298

Reputation: 147

Triggering an action in nested Components in Ember.js

I have a Component--which is essentially a form--displaying editable prices for a set of items. Each row in this form is also a Component, so there's a nested relationship (a parent Component and child Components).

At the bottom of this form is a button to Cancel any changes the user made to the form, meaning it will need to affect all of the child Components. Ideally, I'd like to trigger an action from the Cancel button and have the child Components react to that.

I know this is against the Data Down / Actions Up methodology of Ember, but I'm not sure how else to approach this.

Is there any way to do this?

Upvotes: 4

Views: 910

Answers (1)

GJK
GJK

Reputation: 37369

Following the data-down, actions-up approach, you'll have to do something like this.

Parent component:

App.ParentComponent = Ember.Component.extend({
    isCancelled: false,
    actions: {
        cancel: function() {
            this.set('isCancelled', true);
        }
    }
});

Parent template:

{{child-component isCancelled=isCancelled}}
<button {{action 'cancel'}}>Cancel</button>

Child component:

App.ChildComponent = Ember.Component.extend({
    isCancelled: false,
    wasCancelled: function() {
        if (this.get('isCancelled')) {
            // Cancelled logic here
        }
    }.observes('isCancelled')
});

I'm not sure exactly what you want to happen to the child component when the cancelled button is pressed, but you can probably use computed properties instead of an observer (which I think is a bit cleaner).

Upvotes: 1

Related Questions