Frage

I am 3 months into learning KnockoutJS and it has been great so far. However, I am facing an issue with binding. This is the scenario:

  1. I am using MVC with KO.
  2. MVC model is passed down to the view, converted into a knockout object and pushed into the viewModel variable:

    var data = ko.mapping.fromJS(@Html.Raw(Json.Encode(Model))); var viewModel = new HP.ViewModels.CertificationPathViewModel(data); ko.applyBindings(viewModel);

  3. Within viewModel, I reference the MVC model as self.data:

    ViewModels.CertificationPathViewModel = (function (data) { var self = ViewModels.BaseEntityViewModel.apply(this, [data]); // some other code return { Data: self.Data, }; }

    ViewModels.BaseEntityViewModel = (function (data) { var self = this; self.data = ko.observable(data); // other code return { Data: self.data, }; }

  4. On the view, I data-bind like this:

    <div id="drpControl" data-bind="CustomDropdown: Data().BusinessUnits.SelectedGroup, optionSettings: { CustomOptions: Data().Units.Groups, CustomOptionsCaption: '-- Select Group --' }"></div>

I try to update the self.data after an ajax call. I return the entire MVC model object and attempt to replace self.data like this :

self.data(updatedModel)

My expectation is that KO will take care of the update and no extra binding is needed. It works great for simple binding (ex. Value: Data().Something) but it doesn't work for complex binding (ex. value: Data().BusinessUnits.SelectedGroup ).

The controls that have complex binding are still bound to the old model, so KO doesn't know what to pass back next time I submit an ajax request.

Is this a limitation of KO, or I am not doing something properly?

Thanks

War es hilfreich?

Lösung

the ko.mapping plugin changes every property on self.data into an observable. During your update, you need to remap the updated data.

Since you didn't actually post your code, just unformatted snippets I can't help a whole bunch, but you should start by changing this line: self.data(updatedModel) to this:

ko.mapping.fromJS(updatedModel, self.data);

see the Knockout.JS mapping documentation

Protip for stack overflow - include your full code, to the extent that it's possible. Also, if you can, make a jsfiddle that reproduces your problem.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top