Craig Shearer
Craig Shearer

Reputation: 14521

How do I use the ko.mapping plugin to refresh a part of my view model?

I have a complex view model like this:

    function DiaryBundleViewModel() {
        var self = this;

        self.existingJobSearchViewModel = new ExistingJobSearchViewModel(self);

        self.DiaryBundle = ko.observable();
        self.Appointment = ko.observable();
...

I have bound my view model to my UI as in:

var vm = new DiaryBundleViewModel();
ko.applyBindings(vm);

In my view model, I have a function to fetch an Appointment from the server.

When I get my result back from the server, I do this:

self.Appointment(result);

and the UI updates with the fields showing the appointment.

However, only the Appointment itself is a ko.observable. There are inter-related properties on my Appointment object that I want to fire changes in the UI. So, I need the ko.mapping plugin.

However, I'm stuggling with how to use it in this instance.

If I do this:

self.Appointment = ko.mapping.fromJS(result);

it doesn't work, as the UI is already bound to self.Appointment and I've just overwritten that so it won't see the change.

So, I tried:

ko.mapping.fromJS(result, self.Appointment);

but that doesn't work either.

What am I missing?

Upvotes: 1

Views: 576

Answers (1)

estebane97
estebane97

Reputation: 1138

First you need to create an AppointmentVm and there use the Mapping plugin.

Appointment:

 var AppointmentVm= function(data) {
    ko.mapping.fromJS(data, { }, this);
};

and in you main viewmodel you use:

ko.mapping.fromJS(data, {
        'Appointments': {
            create: function(options) {
                return new AppointmentVm(options.data);
            }
        }
    },this);

This map the children object.

Upvotes: 2

Related Questions