向使用 Knockout JS 映射插件创建的视图模型添加属性 [英] Adding properties to the view model created by using the Knockout JS mapping plugin

查看:22
本文介绍了向使用 Knockout JS 映射插件创建的视图模型添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 Knockoutjs 网站上的映射插件示例.

I am working through the mapping plugin example on the Knockoutjs website.

这是示例数据.

Knockout JS 映射插件

var data = {
    name: 'Scott',
    children: [
        { id : 1, name : 'Alice' }
    ]
}

该示例显示了如何覆盖其中一个子对象的映射,但我如何更改基础对象的映射.

The example shows how to override the mapping for one of the children but how do I alter the mapping for the base object.

例如,如果我想向 Scott 添加一个FavouriteChild"属性,我会怎么做?

If for example I wanted to add a "FavouriteChild" property to Scott how would I go about it?

我假设我需要在基本映射上使用 create 函数,但我在任何地方都找不到语法示例.

I assume I need to use the create function on the base mapping but I cannot find an example of the syntax anywhere.

var myChildModel = function(data) {
    ko.mapping.fromJS(data, {}, this);

    this.nameLength = ko.computed(function() {
        return this.name().length;
    }, this);
}

var mapping = {
    'children': {
        create: function(options) {
            return new myChildModel(options.data);
        }
    }
}

var viewModel = ko.mapping.fromJS(data, mapping);

从下面接受的答案中,我发现这是可行的

EDIT : From the accepted answer below I found this to work

<span data-bind='text: AdditionalProperty'>

淘汰码

var mapping = {
    create: function (options) {
        //customize at the root level.  
        var innerModel = ko.mapping.fromJS(options.data);

        innerModel.AdditionalProperty = 'Hello World';

        return innerModel;
    }
}

var viewModel = ko.mapping.fromJS(data, mapping);

//use this as our model bindings
ko.applyBindings(viewModel);

推荐答案

您需要在映射对象本身上使用 create 方法,例如:

You need to use a create method on the mapping object itself like:

var mapping = {
  //customize at the root level.  
  create: function(options) {
     //first map the vm like normal
     var vm = ko.mapping.fromJS(options.data);

     //now manipulate the returned vm in any way that you like
     vm.someProperty = "test";

     vm.someComputed = ko.computed(function() {
          return vm.first() + " " + vm.last();
     });

     //return our vm that has been mapped and tweaked
     return vm;
  }
};

这篇关于向使用 Knockout JS 映射插件创建的视图模型添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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