0

The objective is to display sorted data received from a REST API call and keep them sorted as data gets updated.

The first render seems to sort the data by itself without the need of a sorting function. But when data is updated based on results of subsequent calls using ractive.set method, I am unable to understand the strange behavior. The updated object retains the 'index' of the key (2012) that repeats in the updated object, even if its value (100) actually changed.

Resetting it to the original value now messes up the order in which it initially rendered the template.

Snippet has a button to simulate replacing content with new data and a button to reset to original data. How do I achieve my objective when both these changes occur. Is there a more ractive way to do this?

var firstList = {
  2014: { count: 10 },
  2013: { count: 20 },
  2012: { count: 30 },
  2011: { count: 50 }
};
var ract = new Ractive({
  template: "#template",
  el: "#output",
  data: {
    shuts: firstList,
    sort: function(obj) {
      const ordered = {};
      Object.keys(obj).sort().forEach(function(key) {
        ordered[key] = obj[key];
      });
      return ordered;
    }
  }
});

$('.change').on('click', function(e) {
  ract.set('shuts', {
    2010: { count: 1 },
    2012: { count: 100 },
    2017: { count: 17 }
  });
});

$('.reset').on('click', function(e) {
  ract.set({
    shuts: firstList
  });
});
.item .year,
.item .count {
  margin: 10px;
}
<script src="https://cdn.jsdelivr.net/ractive/0.8.12/ractive.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="output"></div>
<button class="change">Change</button>
<button class="reset">Reset</button>
<script id="template" type="text/html">
  <p>Sorted by Year</p>
  {{#sort(shuts):year}}
  <div class="item">
    <span class="index">{{@index}}</span>
    <span class="year">{{year}}</span>
    <span class="count">{{shuts[year].count}}</span>
  </div>
  {{/}}
</script>
SarathMS
  • 519
  • 2
  • 6

1 Answers1

2

JavaScript does not guarantee the order of the keys of an object, and neither does Ractive. Implementation is also vendor-specific. Consistency of the implementation is not guaranteed across browsers.

If order is of a concern, consider using arrays instead.

var firstList = [
  { year: 2014, count: 10 },
  { year: 2013, count: 20 },
  { year: 2012, count: 30 },
  { year: 2011, count: 50 }
];
Community
  • 1
  • 1
Joseph
  • 107,072
  • 27
  • 170
  • 214