knockout js best practices ajax error handling

后端 未结 2 1847
滥情空心
滥情空心 2021-02-07 21:51

What best practices for Knockout js have you used when ajax json responses come back bad.

How do you create your mappings to display an error has occured to the user? Ho

2条回答
  •  滥情空心
    2021-02-07 22:28

    The way I've come up with error handling in KO has been to create a base class:

    errorHandlingViewModel = function () {
        var self = this;
        self.ErrorText = ko.observable();
        self.errorHandler = function (jqXHR, textStatus, errorThrown) {
            self.ErrorText('An error has occured, please refresh the page and try again in a little while. (' + textStatus + ':' + errorThrown + ')');
        };
        self.validationErrorHandler = function (err) {
            //todo
            alert('validation error ' + err);
        }
        self.successHandler = function (data, onSuccess) {
            if (data.result == "success") {
                if (onSuccess) {
                    onSuccess(data.data);
                }
            }
            else {
                if (data.data && data.data.Tag) {
                    if (data.data.Tag == "ValidationError") {
                        validationErrorHandler(data.data.Tag);
                    }
                }
                errorHandler(null, data.result, data.data);
            }
        };
    };
    

    This has an observable ErrorText field.

    All my ViewModels that need this error handling can use prototypal inheritance:

    viewModel.prototype = new errorHandlingViewModel();
    var mainViewModel = new viewModel();
    ko.applyBindings(mainViewModel, $("#locationTOApplyBindingTo")[0]);
    

    In this view models ajax calls look like:

    $.ajax({
        type: 'POST',
        url: myURL,
        data: myData,
        success: function (data) {self.successHandler(data,success);},
        error: self.errorHandler
    }); //end ajax
    

    The UI is a simple data-bind:

    Javascript Try-Catch is still missing from this model as I am unsure to the placement

提交回复
热议问题