Using x-sort and x-for to edit json #4383
Unanswered
Senitram666
asked this question in
1. Help
Replies: 1 comment 2 replies
-
Fixed in #4361 |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I am creating a small software, fully web based, to help a friend here publish some art works in a more interactive way.
the whole project should run from a static website, no server or other stuff.
I have a list of pages and I wanted to make this list sortable, so that you can reorder pages, and the page structure is defined and saved into a js object, that the user downloads as a json file.
So I have my variable named project like this
project = {
"title": "ABCDE",
"pages": [
{
"page_id": "LrBH1X",
"subtitle": "A",
"pageNumber": 1,
},
{
"page_id": "v2xxrp",
"subtitle": "B",
"pageNumber": 2,
},
]
}
then, I created a page list using x-for, and added x-sort to allow for reordering pages.
I then added an event handler with splice to update the original pages list to the new order:
reorder_page(item, position, context) {
const index = context.project.pages.findIndex(page => page.page_id === item);
const [page] = context.project.pages.splice(index, 1);
context.project.pages.splice(position, 0, page);
context.project.pages.forEach((item, position) => { item.pageNumber = position+1 });
},
Not much that big of a deal, to this point. but I got a problem when testing:
I reorder the list with x-sort, it all goes right.
my function gets called, and the data is correctly reordered to match the new order.
then, alpine watches that I changed the array, and reevaluates x-for, updating the list to the same order saved in my variable.
At last, x-sort reapplies the last sort operation, so my list goes like this:
(I'll write the page-pagenumber, in the order that it shows here. the page number reflects the order the item is saved in the js object)
A-1, B-2, C-3, D-4, E-5
if I change for example, B to go to between D and E, I get:
A-1, D-3, B-4, C-2, E5
Because X-sort is applying the order to the new list, it's like the reorder is applyed twice.
If I could 'reset' the x-sort after my handler function, so that it won't reapply the changes when disabled, I think that this could solve it.
So that in normal cases, the default works fine, but when a user function manually reorders the variable to apply the changes made with x-sort, it won't get the changes made twice. (I get that x-sort does this to keep the order if some value change causes x-for to redraw the list from the original array, but having the option to 'reset' this behavior would be good to let users interact with this order manually.)
Beta Was this translation helpful? Give feedback.
All reactions