ko.mapping可以优雅地包装getter和setter吗?

时间:2016-02-11 16:15:33

标签: knockout.js typescript knockout-mapping-plugin

我将Knockout与TypeScript结合起来。考虑这个例子:

ParticipantObjects[0]

转化为:

class Person
{
    public FirstName:string = "John";
    public LastName: string = "Doe";

    public get FullName(): string
    {
        return this.FirstName + " " + this.LastName;
    }

    public set FullName(fullName: string): void
    {
        var names = fullName.split(" ");
        this.FirstName = names[0];
        this.LastName = names[1];
    }
}

调查:

var Person = (function()
{
    function Person()
    {
        this.FirstName = "John";
        this.LastName = "Doe";
    }

    Object.defineProperty(
        Person.prototype,
        "FullName",
        {
            get: function()
            {
                return this.FirstName + " " + this.LastName;
            },
            set: function(fullName)
            {
                var names = fullName.split(" ");
                this.FirstName = names[0];
                this.LastName = names[1];
            },
            enumerable: true,
            configurable: true
        });

    return Person;
})();

这根本不起作用。 是否有可能使ko.mapping以通用的可重用方式理解getter和setter?

1 个答案:

答案 0 :(得分:0)

您可以通过将fullName定义为计算函数来自己完成:

var Person = function() {
  var self = this;

  self.firstName = ko.observable('John');
  self.lastName = ko.observable('Doe');

  self.fullName = ko.computed({
    read: function() {
      return self.firstName() + ' ' + self.lastName();
    },
    write: function(name) {
      if( name ) {
        var names = name.split(' ');
        self.firstName(names[0]);
        self.lastName(names[1]);
      }
    }
  });
};

我从来没有对复杂物体的ko.mapper好运,并且喜欢自己处理它,它真的不是很多工作。