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?

4

1 回答 1

0

应该可以创建一个返回排序列表的计算

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;
});

当任何距离属性发生变化时,此列表应自动更新。

于 2014-07-09T16:44:34.450 回答