简体   繁体   中英

Data binding issue with knockout and revealing module pattern

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.

In your loadPatient function you are replacing the patient variable with a new object, but your module already returned a reference to the original observable. So, updating it in this way will not update what the object returned.

Here is an option: http://jsfiddle.net/rniemeyer/pp9ym/6/

Basically, you keep patient as an observable and then update it in your loadPatient function. In your view, using the with binding can help you protect against your object being null, in case you want to load it after you call ko.applyBindings .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM