Vicenç Gascó
Vicenç Gascó

Reputation: 1346

How to nest components in a proper way

I'm starting with EMBER.js, and there are some doubts that I have:

Let's say that I am creating a simple chat, just for the example. I have a left-side panel with a list of users, and a right-side panel with the messages sent.

I considered creating a component called: users-list, that displays a list of users. Every member of that list should be another component called user.

This means that a user component is responsible of drawing itself, with the user name, last sent message, name color, etc... (all are properties) and also has some actions in buttons beside its name: changeName, changeColor, leaveRoom.

While a users-list is responsible for maintaining a list of users and displaying them using the user component.

So the questions here are:

  1. Is this the proper way to go?
  2. If it is: How can I delete an item from the users-list component, from an action inside of the child user component (leaveRoom action)?
  3. If not: How should I implement that? I'd like to keep responsibilities isolated.

Upvotes: 0

Views: 35

Answers (1)

Daniel
Daniel

Reputation: 18682

  1. Is this the proper way to go?

Yes, it is. But you have to use hyphen in component name, so user component should become something like this: user-component.

If it is: How can I delete an item from the users-list component, from an action inside of the child user component (leaveRoom action)?

See WORKING DEMO.

In users-list template pass an action (defined in users-list) to user-component:

{{#each model as |user|}}
    {{user-component model=user leaveRoom=(action 'leaveRoom')}}
{{/each}}

Action leaveRoom in users-list:

actions: {
  leaveRoom(user) {
    alert('User-list: user ' + user.name + ' wants to leave room.');
  }
}

Then, we have simple user-component template with button that fires an action leaveRoom of user-component:

{{model.name}} - <button {{action 'leaveRoom' model}}>Leave room</button>

Action leaveRoom in user-component calls action passed to component from users-list. So, leaveRoom in user-component looks like this:

actions: {
  leaveRoom(user) {
    this.get('leaveRoom')(user);
  }
}

Upvotes: 1

Related Questions