Knockout mapping using JS methods

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

  • I am making a receive request that returns JSon data. Same properties as my ViewModel knockout.
  • I use the mapping plugin to convert my JSon result to a knockout view model.

This works fine, but of course I am losing the methods defined in my knockout model.

How to prevent this, so I can use the mapping and save my methods?

Many thanks!

Update

This is just a sample. There may be some syntax errors, but it should show what I'm 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; }
}

Result of my server

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

ko, json viewmodel. , , json viewModel.people. , .

+3

All Articles