【问题标题】:Knockout not updating the Viewmodel淘汰赛未更新 Viewmodel
【发布时间】:2016-08-19 03:32:31
【问题描述】:

我有一个淘汰脚本,它有一个默认视图模型,字段值很少。当我在表单中输入数据并提交时,它不会发回任何更新的值。例如,邮政编码保持我在默认加载时定义的值。这是代码

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

`

【问题讨论】:

  • 一般发生在代码有错误的时候。您是否尝试过运行它 jsfiddle。

标签: knockout-2.0


【解决方案1】:

问题可能是您甚至在页面加载之前就运行了敲除绑定,或者您尝试在按代码执行顺序创建 ViewModel 之前访问它。最后一件事是创建模型的新实例总是比将其分配给自己更好。

我在下面的小提琴中创建了它们。它似乎有效

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

$(document).ready(function() {

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

【讨论】:

  • 在 Knockout 中使用声明式绑定,我不应该检查 ready 函数。因此,在您的代码中,如果您取出 .ready 函数,它仍然具有相同的行为。所以这不是解决方案。
  • Ramki,来自这个文档“自我调用功能只能在你的页面底部工作”——因为我在底部有 ko.applyBindings(xxx),它不需要文档。准备好。除此之外,您的 jsfiddle 实际上为我指出了一个解决方案。我正在使用 ViewModel = new ViewModel(defaultmodel); ko.applyBindings(ViewModel);
  • 除此之外,您的 jsfiddle 实际上为我指明了解决方案。我的变量名称应该与“ViewModel”不同,因为它是主模型的名称,如下所示 vm=new ViewModel(defaultmodel); ko.applyBindings(vm);至于没有显示的数据,我不得不使用 var m = ko.mapping.toJS(self);
猜你喜欢
  • 1970-01-01
  • 2013-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多