敲除映射如何添加和更新 [英] Knockout mapping how to add and update

查看:77
本文介绍了敲除映射如何添加和更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的js对象

I have a js object that looks like the following

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

我希望至少可以观察到"IsNew".为此,我使用了ko.mapping插件

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)

但是我还需要在我的vm上具有可观察到的"SelecetedMessage"和SetSelected函数.但是我不确定将这些作为我的vm的最佳方式.

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?

推荐答案

听起来您需要设置viewModel映射以将扩展属性添加到消息中.它应该看起来像这样:

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

这篇关于敲除映射如何添加和更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆