我的情况是我想覆盖 set
knockout 对 observables 的方法;并举例说明我为什么要这样做,请使用以下示例代码:
this.magic = ko.observableArray();
// ... inside an Ajax request
var formatted = reduceAndFormat(respone);
this.magic(formatted);
这重复了几次,所以我想移动
reduceAndFormat
的整个主体。 set
中的函数可能自定义的 observable 的方法。有没有办法做到这一点?因为除了订阅可观察的更新之外,文档中没有看到太多其他内容。
最佳答案
您可以创建一个 writable computed observable
可能是这样的:
// private variable
this._magic = ko.observableArray();
// property with getter and setter
this.magic= ko.computed({
read: function(){
return _magic();
},
write: function(value) {
var formatted = reduceAndFormat(value);
this._magic(formatted);
}
});
关于knockout.js - 覆盖 observable/observable Array set 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11259639/