bitovi/canjs — pull request #88 by daffl (2013-01-16 22:49:45+00:00)
Title: Observe.List sort plugin erroring on item removal

Ran into this when testing some new functionality when implementing the sort plugin for Observe.List (in conjunction on a Model.List).

When removing the last item in the list, an error is thrown stating that the "item is undefined".

In "can/observe/sort/sort.js", lines 142-170:
```javascript
proto._changes = function(ev, attr, how, newVal, oldVal){
if(this.comparator && /^\d+./.test(attr) ) {
// get the index
var index = +/^\d+/.exec(attr)[0],
// and item
item = this[index],
// and the new item
newIndex = this.sortedIndex(item);

if(newIndex !== index){
// move ...
[].splice.call(this, index, 1);
[].splice.call(this, newIndex, 0, item);

can.trigger(this, "move", [item, newIndex, index]);
ev.stopImmediatePropagation();
can.trigger(this,"change", [
attr.replace(/^\d+/,newIndex),
how,
newVal,
oldVal
]);

return;
}
}

_changes.apply(this, arguments);
};
```
At line 149, `newIndex = this.sortedIndex(item)` throws an error because `item` doesn't exist in the List any longer. A little check to see if `typeof item != "undefined"` fixes the issue.

Revised method:
```javascript
proto._changes = function(ev, attr, how, newVal, oldVal){
if(this.comparator && /^\d+./.test(attr) ) {
// get the index
var index = +/^\d+/.exec(attr)[0],
// and item
item = this[index];

if( typeof item != 'undefined') {
// and the new item
var newIndex = this.sortedIndex(item);

if(newIndex !== index){
// move ...
[].splice.call(this, index, 1);
[].splice.call(this, newIndex, 0, item);

can.trigger(this, "move", [item, newIndex, index]);
ev.stopImmediatePropagation();
can.trigger(this,"change", [
attr.replace(/^\d+/,newIndex),
how,
newVal,
oldVal
]);

return;
}
}
}

_changes.apply(this, arguments);
};
```