kitty sarvaj kitty sarvaj - 4 months ago 12
Ajax Question

Knockout JS binnding the ajax result

I am new to Knockout JS, I am trying to bind the ajax result data to Knockout JS viewmodel, but I am facing the problem while binding the data to view, I have create model and viewmodel and I am getting the result from ajax. Need help.

Below is my code:

// ajax on page load///
$.ajax({
type: "POST",
dataType: "json",
url: baseUrl + 'api/xxx/xxx',
data: UserProfileModel,
success: function(data) {
result = data;
////view model////
userDetailsViewModel(result);
},
error: function(error) {
jsonValue = jQuery.parseJSON(error.responseText);
//jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});

//// view model///
var userDetailsViewModel = function(result) {
console.log(result);
self = this;
self.user = ko.observable(new userModel(result));
};

$(document).ready(function() {
ko.applyBindings(userDetailsViewModel());
});

/// Model////
function userModel(result) {
this.name = ko.observable();
this.userName = ko.observable();
}

Answer
  1. Your userDetailsViewModel is a function that returns undefined. You'll either have to use new or create a return statement if you want it to create an actual viewmodel. E.g.:

    var UserDetailsViewModel = function(result) { 
      var self = this;
      self.user = ko.observable(new UserModel(result));
    };
    
    var mainUserDetailsViewModel = new UserDetailsViewModel(data);
    
  2. You'll have to store a reference if you want to update your viewmodel from the scope of the ajax callback. Alternatively, you could make the ajax functionality part of the viewmodel. The easiest example:

    var mainUserDetailsViewModel = new UserDetailsViewModel(data);
    
    $.ajax({ 
      success: function(data) {
        mainUserDetailsViewModel.user(new UserModel(data));
      }
    });
    

    Make sure you use this model in your applyBindings call:

    ko.applyBindings(mainUserDetailsViewModel);
    

Note that I've used CapitalizedNames for functions that need to be instantiated, and uncapitalizedNames for instances of those functions. Following default naming conventions might help keeping track of what's what.