Mhoque
Mhoque

Reputation: 377

Knockout not updating the Viewmodel

I have a knockout script that have a defaut viewmodel with few fields values. When I have entered the data in the form and submit, it is not sending any updated value back. For example, the zipcode stays the value I defined on the defaul load. Here is the code

$(function () {
    ViewModel.zipCode.subscribe(function (value) {
        $.get("/api/abc/GetCounties?zipCode=" + value, null, ViewModel.county, 'json');       
    }.bind(this));
});

var ViewModel = function (data) {
    var self = this;

self.zipCode = ko.observable(data.zipCode);
self.dateOfEvent = ko.observable(new Date());

//Enrollment reasons
self.enrollmentReasons = ko.observableArray(new Array());
$.get("/api/abc/reasons", null, self.enrollmentReasons, 'json');

//county from Zipcode subscribed
self.county = ko.observableArray(new Array());
$.get("/api/utilityapi/GetCounties?zipCode=" + data.zipCode, null, self.county, 'json');

self.selectedChoice = ko.observable();
self.applicants = ko.observableArray();
self.applicants.push(new getaquoteapplicant());

//IsValid zip subscribed
self.isValidZip = ko.observable(false);


//operations
self.addApplicant = function () { self.applicants.push(new getaquoteapplicant()) };
self.removeApplicant = function (getaquoteapplicant) { self.applicants.remove(getaquoteapplicant) };
self.save = function () {       
    $.ajax({
        url: '/xyz/start',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(data),
        success: function (result) {
            window.location.replace('/getaquote/planoptions', result);
        }
    });
}

}

var getaquoteapplicant = function () {
    var self = this;
    self.coverageFor = [
        { name: "Self" },
        { name: "Spouse/Life Partner" },
        { name: "Son" }
    ];

    self.dateofBirth = ko.observable();
    self.tobaccoUser = [
        { name: "Yes", value: true },
        { name: "No", value: false }
    ];
};
var defaultmodel = {
    dateOfEvent: new Date(),
    selectedChoice: 4,
    zipCode:55044
}

ViewModel = new ViewModel(defaultmodel);
ko.applyBindings(ViewModel);

`

Upvotes: 0

Views: 71

Answers (1)

Ramki
Ramki

Reputation: 381

The problem could be that you are running the knockout binding even before the page is loaded or that you trying to access the ViewModel before it is created in the code execution order. One last thing is that always better to create a new instance of the model rather than the assigning it to itself.

I have created them in the fiddle below. It seems to work

https://jsfiddle.net/ramkiFiddle/npsgq8uL/1/

$(document).ready(function() {

  var viewModel = new ViewModel(defaultmodel);
  ko.applyBindings(viewModel);
});

Upvotes: 1

Related Questions