Knockout mapping how to add and update

2019-08-15 04:27发布

问题:

I have a js object that looks like the following

{Messages: [
    {Content: "some content",
    Id: "203",
    IsNew: false,
    Subject: "some Subject"},
    ....
]}

I would like for 'IsNew' to be observable at the very least. To do this I was using the ko.mapping plugin

//Within success of ajax call
var vm = ko.mapping.fromJS(data)

But I also have a need for a 'SelecetedMessage' observable and a SetSelected function on my vm. But im not sure the best way for these to be a part of my vm.

Could someone explain how I might include these properties on my vm, and when i update the vm with an updated list of messages, how to keep these properties untouched?

回答1:

It sounds like you need to set up a viewModel mapping to add extended properties to your messages. It should look something like this:

var Message = function(data) {
   var self = this;
   ko.mapping.fromJS(data, { }, self);
   self.isNew = ko.observable(false);
   // Add more message-specific observables or functions you need here
};

var viewModelMapping = {
    'Messages': {
     create: function(options) {
            return new Message(options.data);
        }
    };

var ViewModel = function(data) {
    var self = this;
    // Add more view model-specific observables or functions you need here

    ko.mapping.fromJS(data,viewModelMapping,self);
}

$(document).ready(function () {
    vm = new ViewModel(initialViewModelData);
    ko.applyBindings(vm);
});


You can read more in the Customizing object construction using “create” and Customizing object updating using “update” sections here