views:

19

answers:

1

I am developing a web-app which displays a list of products(say 10 items) for the user. The user has the option to sort the result by price, brand etc. The data is loaded from the database and it is pretty small list. How do I do sort the results by their attributes, which is constant. Enlighten me on implementing the client side sorting. Does dojo toolkit offers anything for sorting a small list based on a user input.

The reasons why I am convinced with client-side sorting are:

  • The result set is small, upto 10 items and can be displayed in a single page.
  • Secondly, all the attributes of the item(for sorting) are available in the client side and no need a database hit.

Correct me if I am wrong; Also, please let me know if there are any issues in this approach / do I miss anything important?

Looking for valuable comments.

Thanks in advance.

EDIT: To be precise, I am working on designing a WishList and it has only selected items. The user has the option to sort by price(low to high or vice-versa), brand name(A-Z or Z-A). I will be displaying the whole row and I need to provide sorting on all the attributes of the row based on a combo box selection. Can I accomplish this using dojo AJAX or plainly JavaScript?

+1  A: 

You'll probably want to use AJAX for this, because if a user sorts by a different column, e.g. price, she's going to want the cheapest product of them all, not just the one's you're showing. I'm not sure what Dojo has for doing Ajax, but in Prototype, it's pretty easy:

http://prototypejs.org/learn/introduction-to-ajax

If you really only want to sort the items that are currently being displayed, use Array.sort:

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/sort

Suppose your items are shown as rows in a table. Using Prototype, you can gather these up in an array like so:

var items = $$('tr.item');

Then, you would use the sort method to sort the items array:

items.sort(function (i1, i2) {
  return price(i1) - price(i2);
})

Then, replace the contents of the table:

var t = $$('table.items');
t.update();
items.each(function (i) { t.appendChild(i); });
allyourcode
Many thanks for the response. Though I had initial difficulty in understanding your code, I figured it out:). If this is based on many attributes of that product object rather than the price alone?
chong
Replace price with whatever you want to sort by. You can even make that one of the parameters to your table sort function eg function sort_items(by) { ... items.sort(function (i1, i2) { return by(i1) - by(i2); }); ...}. PS: if this answered your question, would you mind marking it as the accepted answer? Thanks :)
allyourcode