5
votes

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 }
                                }
        };
1
can you show us how you're doing mapping or link to jsfiddle? - frennky
jsfiddle is not really posible. I have tried ko.mapping.fromJSON and ko.mapping.fromJS. The question is, how to do it right. - dknaack
one option would be reapply the model binding each time you change the model data with any ko.mapping.fromJS mapping. - ashraf

1 Answers

3
votes

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.