Knockout.js 如何将计算属性添加到集合中?

Knockout.js 如何将计算属性添加到集合中?,knockout.js,knockout-mapping-plugin,Knockout.js,Knockout Mapping Plugin,我正在使用Knockout并将一个可观察的集合绑定到标记 如果我可以为集合中的每个项添加一个计算函数,那就太好了,但我不确定如何在Knockout中正确地执行此操作 例如,给定此模型: var model = { 'persons' : [ { firstName: "John", lastName: "Smith" }, { firstName: "Sgt.", lastName: "Shiney-Sides" }, { firstNam

我正在使用Knockout并将一个可观察的集合绑定到标记

如果我可以为集合中的每个项添加一个计算函数,那就太好了,但我不确定如何在Knockout中正确地执行此操作

例如,给定此模型:

var model = {
    'persons' : [
        { firstName: "John", lastName: "Smith" },
        { firstName: "Sgt.", lastName: "Shiney-Sides" },
        { firstName: "Rusty", lastName: "Schacklefurt" }
    ]
};

ko.applyBindings(model);

我想添加一个连接名字和姓氏的
fullName
计算函数。

您可以使用

代码如下所示:

var model = {
    'persons' : [
        { firstName: "John", lastName: "Smith" },
        { firstName: "Sgt.", lastName: "Shiney-Sides" },
        { firstName: "Rusty", lastName: "Schacklefurt" }
    ]
};

// specifies the create callback for the 'persons' property
var mappingOptions = {
    'persons': {
        // overriding the default creation / initialization code
        create: function (options) {
            var Person = function () {
                this.fullName = ko.computed(function () {
                    return this.firstName() + ' ' + this.lastName();
                }, this);

                // let the ko mapping plugin continue to map out this object, so the rest of it will be observable
                ko.mapping.fromJS(options.data, {}, this);
            };
            return new Person();
        }
    }
};

model = ko.mapping.fromJS(model, mappingOptions);

ko.applyBindings(model);

归功于。

您可以使用

代码如下所示:

var model = {
    'persons' : [
        { firstName: "John", lastName: "Smith" },
        { firstName: "Sgt.", lastName: "Shiney-Sides" },
        { firstName: "Rusty", lastName: "Schacklefurt" }
    ]
};

// specifies the create callback for the 'persons' property
var mappingOptions = {
    'persons': {
        // overriding the default creation / initialization code
        create: function (options) {
            var Person = function () {
                this.fullName = ko.computed(function () {
                    return this.firstName() + ' ' + this.lastName();
                }, this);

                // let the ko mapping plugin continue to map out this object, so the rest of it will be observable
                ko.mapping.fromJS(options.data, {}, this);
            };
            return new Person();
        }
    }
};

model = ko.mapping.fromJS(model, mappingOptions);

ko.applyBindings(model);

jonathanconway的答案是正确的,但是有点落后,而且大集合占用大量内存,因此将类的声明从create方法中移出

然后从create函数调用构造函数,如下所示

create: function (options) {
   return new Person(options);
}

为了节省更多的内存,您可以将计算出的声明移到原型声明中。

@jonathanconway的答案是正确的,但是有点落后,而且对于大型集合,它占用大量内存,请将类的声明从create方法中移出

然后从create函数调用构造函数,如下所示

create: function (options) {
   return new Person(options);
}
为了节省更多的内存,您可以将计算结果移动到原型声明中