KnockoutJS – Frustrations with ko.computed and an AJAX request

KnockoutJS – Frustrations with ko.computed and an AJAX request

Asked on December 21, 2018 in knockout js.
Add Comment


  • 3 Answer(s)

        Doing in this way is wrong due to the call being made running multiple thing at a time . The “read” function sent  back before the response is retrieved.

        Try to do something like this:

    function viewModel() {
        var self = this;
        this.Id = ko.observable("@Model.Identity()");
        this.Points = ko.observable(0);
        var refreshPoints = function() {
            $.ajax({
                url: '/skills/points',
                data: { id: self.Id() }, // <-- you need () here!
                type: 'get',
                success: function (data) {
                    self.Points(data);
                }
            });
        };
        // Now subscribe to the ID observable to update the points whenever the 
        // ID gets changed:
        this.Id.subscribe(refreshPoints);
    }
    
    Answered on December 21, 2018.
    Add Comment

        First, Bind the  observable variable to the html variable and then update this to ko.computed field. Binding straightly  the ko.computed field to the html variable is not good.

    self.htmlUserName = ko.observable();
    self.computedUserName = ko.computed(function () {
    $.ajax(
        ....
        success: function (result) {
            self.htmlUserName(result);
        }
    }
    
    Answered on December 21, 2018.
    Add Comment
    • Knockout binding is not fit to  irregular computations .
    • Use the synchronous property and place it to the end of the AJAX request .
    • The user can this as observable by re-sending the AJAX request in the change handler for the dependent property.
    • Try this  separate placeholder value to including a loading indicator to the bound UI .
    Answered on December 22, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.