Premkumar
Premkumar

Reputation: 111

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.

Upvotes: 0

Views: 1422

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

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.

Upvotes: 4

Related Questions