Knockout mapping how to add and update

﹥>﹥吖頭↗ 提交于 2019-12-24 11:32:05

问题


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



来源:https://stackoverflow.com/questions/15282748/knockout-mapping-how-to-add-and-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!