Search code examples
jsviews

jsViews sort - how to automatically update the sort when a property changes


Just looking at the live example code on the jsViews site: https://www.jsviews.com/#jsvfortag@jsvsortfilterrange

If I modify this line to include a sort:

{^{for members sort='name' start=start-1 end=end}} 

The array does not re-sort after observably adding an item to it.

$.observable(team.members).insert(0, {name: "zzz this should be last"})

Any ideas how to trigger the sort after an item is inserted?


Solution

  • The sorting does refresh when there is an array change event. Putting sort='name' will re-sort if you click on [Add], or on [x] to delete an item. But what you want it is to trigger a re-sort whenever you change the name property in an item.

    But you don't want it to re-sort on character entry, so the first thing is to set:

    <input data-link="name trigger=false" />
    

    See docs here for the trigger setting (done above as local override of the global setting).

    Next you can declaratively make your list of items depend on the name text on each of the items, by writing

    {^{for members sort='name' depends='members.[]^name'}}
    

    The depends='members.[]^name' feature has very little documentation, but is a wild card for responding to individual property changes (here, the name property) on any item in the array.

    See https://www.jsviews.com/#samples/sort-filter@jsv-for for a sample which uses it.

    You could also do depends='members.[]^*' for responding to changes on any array item property.

    And depends='members.**' will work too, for listening to any change at all under the members array (See the docs here)

    Here is a working sample which uses the depends='members.[]^name' approach above:

    https://jsfiddle.net/BorisMoore/b51tu27n/