1

有没有办法动态替换 ko.computed 中正在写入和读取的字段?例如,使用此函数,我想将 self.JobStartDate 替换为可以传入的变量字段名:

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

    var computedDateFn = {
        read: function() {
            return formatDate(ko.utils.unwrapObservable(self.JobStartDate), true);
        },

        write: function(value) {
            var jsonDate = "/Date(" + Date.parse(value).getTime();
            self.JobStartDate(jsonDate);
        }
    }

    this.formattedStartDate = ko.computed(computedDateFn);
    this.formattedEndDate = ko.computed(computedDateFn); // this guy would need the field it writes to/reads from to be self.JobEndDate
}
4

1 回答 1

2

如果您将 computedDateFn 设为接受您的字段名作为字符串并返回定义您计算的 observable 的对象的函数,您可以使用这样的数组表示法......

http://jsfiddle.net/bczengel/tMTCV/

于 2012-05-20T21:00:02.290 回答