问题
This question came out after solving this problem thanks to @nils and I hope someone can help me!
Actually I have a list of records and I can select some of then and remove those with one click.
The code above is working as it should be but I am not sure if what I am doing is right or if it can break any time!
So there I doing the HTTP Request to delete the record inside of the Array.filter()... is that right? I feels that it is quite not right!
deleteSelected() {
this.list = this.list.filter(function(val, i) {
var id = val.id.toString();
if (this.selected.indexOf(id) === -1) {
return true;
} else {
this.$http.delete('/sources/' + id)
.then(function() {
return false;
}, function() {
return true;
});
}
}, this);
this.selected = [];
},
The array this.list
is where are my list of objects and the this.selected
array contains the ID's selected to be removed.
Then if the HTTP request goes ok I remove the obj and if not I keep it!
How do you think is a good way to do that?
---------EDIT---------
Adding a JSBin to be clear what I need!
Actually I just found a problem on my script... It does not wait for the ajax response to remove the item from the array so if some of those record couldn't be deleted it is gonna be removed from the array as well
Somebody?
JS Bin
回答1:
What I do is something like:
<ul>
<li v-for="item in list" @click="deleteItem(item)"></li>
</ul>
So you basically pass the list item to the delete method which in turn does:
deleteItem: function(item) {
# Ajax delete request
.successs(
this.list.$remove(item);
)
Does that solve your problem?
回答2:
As I though that code does not worked but I found a good solution!
It's not working because it is a mass delete so each delete is one request but I've made everyone at once and the script does not wait for the answer to remove the item from the list! If the record does not end up deleted by some validation it will be removed from the list as well!
So what I did is send all delete requests and when the last one finish I make a new request to get to entire list updated!
Here is the code:
// block the records list
$(this.$els.dataGrid).block();
// init a counter
var itemsProcessed = 0;
// get length of records to be deleted
var length = this.selected.length;
// looping to delete one for each
this.selected.forEach((item) => {
// removeLossReasonById() is a method that mand the HTTP DELETE request and then()
this.removeLossReasonById(item).then((response) => {
// if does not delete for any reason show a notify
if (!response.ok)
$.Notification.error(response.data);
// increment the counter
itemsProcessed++;
// if is the last iteration it's gonna unblock the records list and clear my array of items to be removed
if (itemsProcessed === length) {
this.selected = [];
this.getLossReasons().then(() => $(this.$els.dataGrid).unblock());
}
});
});
Hope it helps someone!
来源:https://stackoverflow.com/questions/36379439/http-request-to-remove-record-and-then-remove-obj-from-array-vue-js