5

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 }
                                }
        };
Community
  • 1
  • 1
dknaack
  • 60,192
  • 27
  • 155
  • 202
  • can you show us how you're doing mapping or link to jsfiddle? – frennky Jul 20 '12 at 19:03
  • jsfiddle is not really posible. I have tried `ko.mapping.fromJSON` and `ko.mapping.fromJS`. The question is, how to do it right. – dknaack Jul 20 '12 at 19:07
  • one option would be reapply the model binding each time you change the model data with any ko.mapping.fromJS mapping. – ashraf Jul 21 '12 at 00:43

1 Answers1

3

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.

John Papa
  • 21,880
  • 4
  • 61
  • 60
  • Ok, right. But what should i do if i want that the people model has a method ? `myViewModel.people[0].someMethod()` – dknaack Jul 20 '12 at 17:52
  • OK. Can you work up a fiddle and I can show you some options? – John Papa Jul 20 '12 at 18:13
  • Done, hopefully you understand my problem. Thank you very much in advance. – dknaack Jul 20 '12 at 18:36
  • Here is the same question, answered by RPNiemeyer. http://stackoverflow.com/questions/8401799/knockoutjs-adding-observable-properties-and-functions-to-objects-in-a-mapping-g – John Papa Jul 21 '12 at 01:56