2

I've gotten KO to play nice with asp.net mvc wit a few simple steps:

  1. var jsonModel = @Html.Raw(Json.Encode(Model));
  2. model = ko.mapping.fromJS(jsonModel);
  3. ko.applyBindings(model);

voila, i can now use my serverside model directly in KO bindings.

<input type="text" data-bind="value: Name" />

if i want to extend the main model, that is pretty simple:

    model.blurevent = function(o,x) {
        var src = x.srcElement;
        alert(src.value);
    };

next, i'd like to extend sub classes of the model. For example my model has a Resume class which has Employers collection. I would like to add client side events to the Employer class.

So, if this was just a pure javascript solution i could do something like this:

function Employer() {
    this.ShowDetais = function() { this.DetailsVisible(true); }
}

but, since I am serializing the whole model (#1 above) from the server, Employer is not defined. Instead, the serializer just creates an anonymous collection:

model = {
"Resume" : {
  ...
  "Employers": [
  {
    "ResumeEmployerID": 0,
    "Name": "Employer 1",
    "Title": null,
    "EmployedFrom": "\/Date(-62135578800000)\/",
    "EmployedTo": null,
    "GeneralDescription": null,
    "ProjectHighlights": {

    }
  }
 }

As you see, with the default json serializer, it doesn't bother to define each class used in the model separately (the way one would do this in a pure javascript app) so there is no way to extend sub classes on the client.

I am wondering if this has been addressed? Is there a serializer that will create a more formal model that would be more extensible?

1 Answer 1

1

I think this plugin will hopefully meet your needs

Knockout Mapping

It should deep map your object

This question has a good example I think? Knockout.js and mapping plugin not deep translating

Sign up to request clarification or add additional context in comments.

2 Comments

i am using this plugin. that's what "model = ko.mapping.fromJS(jsonModel);" is.. still don't see a straight forward way to extend sub models. i see that the documentation does touch on customizing object creation.. i'll have to dive into that a bit
ok i see in the "Customizing object construction using “create”" section i might be able to do exactly what i need. will do some proof of concept later today, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.