Shaun Luttin Shaun Luttin - 5 months ago 12
Javascript Question

Pass an object directly to a value converter instead of manually copying it to a new object

We are passing an object parameter to the following value converter.

export class SortValueConverter {
toView(array, config) {
// do stuff
}
}


We pass the object to the value converter by manually copying it to a new object.

<select value.bind="config">
<option repeat.for="s of sortOptions"
model.bind="s.config">${s.friendlyName}
</option>
</select>

<div repeat.for="u of users | sort:{ prop: config.prop, dir: config.dir}">


We would like instead to pass the object directly.

<div repeat.for="u of users | sort:config">


How can we do that?

Answer

You should be able to do it exactly the way you would like. Check this example: https://gist.run/?id=49d1b3acf5fe7d168909a4f49dca152e

Make sure that you set a default value for your config.

MyItem.html

<select value.bind="config">
    <option repeat.for="s of sortOptions"
            model.bind="s.config">${s.friendlyName}
    </option>
</select>
<div repeat.for="u of users | sort:config">

MyItem.js

export class MyItem {
  users = [];
  config;
  sortOptions = [
    { config: { propertyName: 'aaa', direction: 'ascending' }, friendlyName: 'aaa' },
    { config: { propertyName: 'bbb', direction: 'descending' }, friendlyName: 'bbb' },
    { config: { propertyName: 'ccc', direction: 'descending' }, friendlyName: 'ccc' }
  ];

  constructor(userRepo: UserRepository) {
    this.config = this.sortOptions[0];
  }
}