Quantcast
Channel: Ember.JS - Latest topics
Viewing all articles
Browse latest Browse all 4838

How to handle POJO's, regarding tracking, properly?

$
0
0

Please consider following use-case and please let me know your thoughts :grinning:

//routes/user-edit.js
export default class EditUserRoute extends Route {
  model() {
    // i.e. GraphQL Request, which returns a POJO
    return {
      firstName: 'Michael',
      lastName: 'Knight',
      address: {
        street: 'Schoolstreet 22',
        town: 'New York'
      }
    };
  }
}
//templates/user-edit.js
<UserEdit @user={{this.model}} />
//components/user-edit.js
export default class UserEditComponent extends Component {
  @tracked user = null; // I think this tracked is for nothing, isn't it?

  constructor() {
    super(...arguments);
    this.user = this.args.user;
  }

  @action updateFirstName({ target }) {
     this.user.firstName = target.value; // I know, that {{user.firstName}} is not rerendered if this action is triggered. I just want to know, what's your recommended solution to this issue. Please see below.
   }
}
{{!-- ... --}}
<input placeholder="Firstname" type="text" value={{this.user.firstName}} {{on "input" this.updateFirstName}}>
{{!-- ... --}}
<input placeholder="Street" type="text" value={{this.user.address.street}} {{on "input" this.updateStreet}}>
{{!-- ... --}}
{{user.firstName}}
<br>
{{user.lastName}}
<br>
{{user.address.street}}

Solutions:

  1. Convert the POJO from the model hook into a native Class.
class Address {
  @tracked street;
  @tracked town;

  constructor({ street, town }) {
    this.street = street;
    this.town = town;
  }
}
class User {
  @tracked firstName;
  @tracked lastName;

  constructor({ firstName, lastName, address }) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.address = new Address(address);
  }
}
//routes/user-edit.js
export default class EditUserRoute extends Route {
  model() {
    // i.e. GraphQL Request, which returns a POJO
    return new User({
      firstName: 'Michael',
      lastName: 'Knight',
      address: {
        street: 'Schoolstreet 22',
        town: 'New York'
      }
    });
  }
}
  1. Keep the POJO and use { set } from '@ember/object'
  @action updateFirstName({ target }) { 
     set(this.user, 'firstName', target.value);
  }

For me 1. seems a bit costly. But what is better for the long run? Thanks

3 posts - 2 participants

Read full topic


Viewing all articles
Browse latest Browse all 4838

Trending Articles