Sonic Soul
Sonic Soul

Reputation: 24909

Extending Knockout.js ViewModel in asp.net mvc application

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?

Upvotes: 2

Views: 1290

Answers (1)

Neil
Neil

Reputation: 5239

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

Upvotes: 1

Related Questions