0

I have a CanJS Model.List which I'm rendering using an EJS template like follows:

<% this.each(function(item, index) { %>
    <% if(index < 5 ){ %>
        <li <%= (el) -> el.data("item", item) %> >
            <%= todo.attr('name') %>  (<%= todo.attr('distance') %> miles)
        </li>
    <% } %>
<% }) %>

In my app where I load the data with Model.findAll I iterate all the items and fire off an asynchronous call to update the distance property, I have a listener listing for changes to distance which then sorts the list based on the distance:

$.each(branches, function(i, b) {
    console.log(i, b);
    b.bind('distance', function (x, y, z) {
        console.log("Distance", x, y, z);
        b.save();
        branches.sort();
    });

    // Async call to update distance here...
});

The call to sort() works, I have various console.logs() showing it, but my UI doesn't update.

I'm guessing I need the sort to trigger an event that this.each(...) will notice.

How do I get my View to update when the Model.List is re-sorted?

ramblinjan
  • 6,578
  • 3
  • 30
  • 38
Greg B
  • 14,597
  • 18
  • 87
  • 141

1 Answers1

0

It should be possible to create a compute that returns the sorted list:

var sortedBranches = can.compute(function() {
  var sorted = branches.slice(0);

  Array.prototype.sort.call(sorted, function(first, second) {
    return first.attr('distance') - second.attr('distance');
  });

  return sorted;
});

This list should automatically update when any of the distance attributes changes.

Daff
  • 43,734
  • 9
  • 106
  • 120