简体   繁体   中英

Kendo DataSource: how cancel an update request

I have a kendo UI grid and a datasource. When I call the Update method, I test a variable and if the condition is false, I don't want to send the request.

Currently I have:

 $scope.MySource = new kendo.data.DataSource({
  update: {
            url: function (lista) {
                if (testVariable== true) {           
                    testVariable= false;
                    return "api/Liste/PutLista/" + lista.Id
                }
                else {
                    $scope.MySource.cancelChanges();
                }
            },
            type: "PUT",
            dataType: "json",
            beforeSend: function (req) {
                var auth = $window.sessionStorage.token;
                req.setRequestHeader('Authorization', 'Bearer ' + auth);
            }

If testVariable is false I cancel the update but I still see an ajax request to

http://localhost:61927/index.html with PUT method.

How can I prevent a request if testVariable is false?

You can intercept it right after you click on update. In your kendo grid, use the save event. This event is called every time you press update.

save: function (e) {
    if (testVariable === false) {           
        e.preventDefault();         //prevent default action that kendo does
        $scope.MySource.cancelChanges();
    }
}

If the variable is false, then you prevent the default action and do whatever you want (like cancel changes). If it is true, it will just take the default action and save your row.

Just make sure that the variable testVariable is accessible in this event (global variable, or a local variable that you can set in this event).

The url function is not the place to check if you actually want to make the request. I'm pretty sure there is no way to cancel once it has made it that far.

You may want to try using the requestStart event instead. In some cases, returning false from the event handler will cancel the request (but not in all cases, which might be a kendo bug).

Otherwise, you can just overwrite the sync() function on the DataSource instance, do your checks, then call the base implementation if needed.

          $scope.MySource.sync = function () {
            if(customChecksPass) {
                kendo.data.DataSource.fn.sync.apply(this, arguments);
            }
          };

I also just re-read your question and realized you are using the Grid. The grid widget has a save event that you can bind to, and cancel the call to the DataSource from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM