dknaack
dknaack

Reputation: 60516

Knockoutjs Mapping fromJS keep methods

I use KnockoutJs and its great but i need one thing, and i can't figure it out.

  1. I make a get request that returns JSon data. The same properties like my Knockout ViewModel.
  2. I use the mapping plugin to convert my JSon result into a Knockout viewModel.

That works fine but, off course, i lose the methods defined in my knockout viewModel.

How to prevent that so i can use mapping and keep my methods ?

Thank you very much!

Update

This is just a sample. Maybe there are some syntax errors, but it should show what i am trying to do.

My JavaScript

var MyViewModel = function () {
    var self = this;

    self.id = ko.observable();
    self.subModels = ko.observableArray();

    self.doSomething = function () {
        alert("Hello from " + self.id());
    };
};

var MySubViewModel = function () {
    var self = this;

    self.id = ko.observable();

    self.doSomething = function () {
        alert("Hello from " + self.id());
    };
};

My c# Models

public class MyViewModel
{
    public int Id { get; set; }
    public List<MySubViewModel> SubModels { get; set; }
}

public class MySubViewModel
{
    public int Id { get; set; }
}

My Server Result

return new MyViewModel
        {
            Id = 1,
            SubModels = new List<MySubViewModel>
                                {
                                new MySubViewModel { Id = 1 },
                                new MySubViewModel { Id = 2 }
                                }
        };

Upvotes: 5

Views: 672

Answers (1)

John Papa
John Papa

Reputation: 22328

If you are using the ko mapping plugin, you can map the json object to a model inside the viewmodel. For example, if you are getting a list of people, you might map the json to viewModel.people. That way you can keep your viewmodel's other properties untouched.

Upvotes: 3

Related Questions