jmorrell / backbone.obscura

A read-only proxy of a Backbone.Collection that can be filtered, sorted, and paginated.
http://jmorrell.github.io/backbone.obscura/
MIT License
107 stars 19 forks source link

Possible calculation bug on set sort #12

Closed rkingon closed 10 years ago

rkingon commented 10 years ago

Not sure if this is a bug, or if I need to run the sort as a fuction and parse the stored string as an int.

Check out the SS: https://www.dropbox.com/s/0sedm8cuedtj29e/Screenshot%202014-01-25%2000.13.59.png

It goes: 11, 110, 22

What ya think?

rkingon commented 10 years ago

I ran it through a little function which checks if it's NaN & if not parse as float... not sure if it's the most reliable, but it works. Would love to hear your thoughts thanks! :)

@collection.setSort( (model) -> val = model.get(sortBy) if isNaN(val) then val else parseFloat(val) , sortDir)

jmorrell commented 10 years ago

I suspect you are either storing the values as strings in the model (hence why you have to call parseFloat in your example) or they're being coerced to strings somewhere along the way. Here's a basic sanity check that shows Obscura working:

var collection = new Backbone.Collection([
  { val: 11 },
  { val: 22 },
  { val: 110 }
]);

var proxy = new Backbone.Obscura(collection);

proxy.sortBy('val', 'asc');

console.log(proxy.pluck('val')); // outputs [11, 22, 110]

You're second example is probably exactly what you should be doing if the value is stored as a string, though I don't understand why they would be either strings or NaN. If you can store the value as a number from the beginning you'll likely run into less of javascript's less savory parts.

rkingon commented 10 years ago

Thanks Jeremy, yea- these are stored as strings in the model for some reason... I guess it's because they come from the API that way. Obsurca woulds as expected when using against int's ! :)

jmorrell commented 10 years ago

If you don't have the option to modify the API directly (owned by someone else) you should consider adding a Model#parse method to coerce data to the correct type when you receive the API response: http://backbonejs.org/#Model-parse