开发者

Implementing a client side sort on a page after loading

开发者 https://www.devze.com 2022-12-21 12:28 出处:网络
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 p

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?


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

精彩评论

暂无评论...
验证码 换一张
取 消