0

I am having trouble getting data binding to work with Knockout when using revealing module pattern.

my javascript is like this

var HMS = HMS || {};

$(function () {

    HMS.PatientModel = function () {
        this.Patient_Name = ko.observable();
        this.Patient_Address = ko.observable();
    };

    HMS.PatientViewModel = function () {
        var patient = ko.observable(),
        loadPatient = function () {
            patient = new HMS.PatientModel();
            patient.Patient_Name("Premkumar");
        };
        return {
            patient: patient,
            loadPatient: loadPatient
        };
    } ();

    HMS.PatientViewModel.loadPatient();
    ko.applyBindings(HMS.PatientViewModel);

});

I am unable to get the data binding to work with patient name properly. The HTML div tag has data-bind="text:patient.Patient_Name".

Please refer to the code in jsFiddle http://jsfiddle.net/stprem/pp9ym/1/. I would appreciate if you could tell me what I am doing wrong in data binding.

4

1 回答 1

4

在您的loadPatient函数中,您正在用patient新对象替换变量,但您的模块已经返回了对原始 observable 的引用。因此,以这种方式更新它不会更新对象返回的内容。

这是一个选项:http: //jsfiddle.net/rniemeyer/pp9ym/6/

基本上,您将其保留patient为可观察对象,然后在您的loadPatient函数中对其进行更新。在您看来,使用with绑定可以帮助您防止对象为空,以防您在调用ko.applyBindings.

于 2012-08-16T11:57:46.773 回答