Knockout没有更新Viewmodel

时间:2016-08-19 03:32:31

标签: knockout-2.0

我有一个具有defaut viewmodel的淘汰脚本,其中包含很少的字段值。当我在表单中输入数据并提交时,它不会发回任何更新的值。例如,zipcode保持我在默认负载上定义的值。这是代码

$(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);

`

1 个答案:

答案 0 :(得分:1)

问题可能是您在加载页面之前运行了敲除绑定,或者在代码执行顺序中创建ViewModel之前尝试访问ViewModel。最后一点是,创建模型的新实例总是更好,而不是将其分配给自身。

我在下面的小提琴中创造了它们。它似乎工作

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

$(document).ready(function() {

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