开发者

How to efficiently allow a user to sort a list with AJAX

开发者 https://www.devze.com 2023-02-09 02:24 出处:网络
In my application, users have a list of items that they can put in any order they like. The database schema looks like this:

In my application, users have a list of items that they can put in any order they like. The database schema looks like this:

Items
+ Id : int
+ Name : string
+ Order : int

so when the user puts things in order, it sets the Order field accordingly, so that I can sort it later. Great.

Now, I want to make the sort ajax-y, such that the user can drag and drop items into order (and use up/down arrows), and it will just automagically save everything. (If you're familiar with Netflix, they do a similar thing.)

The issue I'm having is that in order to persist the user's changes as they make them, I will need to do an AJAX call every time they do something. If 开发者_JS百科the user moves an item from position 10 to position 1, that implies that I have to update 10 records in that little ajax call. Meanwhile, the user may have queued up 3 more AJAX calls to update other records.

This seems inefficient and like it might be error prone (due to race conditions and so on, if the AJAX calls take a long time.) Should I be worrying about this? Is there a more efficient way to do this? If it makes a difference, I expect most users will have fewer than 5 items to sort.


Since Javascript can't synchronize code, I agree that it would be difficult to implement code that would be sure to avoid race conditions, although I did find this article on implementing a Mutex in Javascript.

However, personally I think that rather than choose an option that is likely to result in race conditions, I would go with one of the following options:

  • Create a save button above the items, that when clicked will save the order to the database.
  • Create a timer that will save the order every five seconds (or whatever), if something has changed. You would still want a save button for this, so the users could force a save.

I would lean towards the latter. Obviously in both cases you would want some visual cue to the users that they have unsaved changes (like changing the background color of the items, for instance). You would most likely want to implement something that makes sure the user wants to leave the page with unsaved changes if you go with either of those options (like in Gmail, when you have unsaved changes in an email that you are composing).

0

精彩评论

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