我正在尝试在我创建的每个行对象中创建self.tags可观察数组的克隆,其中self.field_name反映值,但self.field_value是每个Line对象的独立值。我有点混淆如何做到这一点,我是否需要手动订阅才能更新其中一个值?
function TechnicalViewModel(){
var root = this;
function Tag(data){
var self = this;
self.field_name = ko.observable(data.field_name)
self.field_value = ko.observable(data.field_value)
}
root.tags = ko.observableArray([
{
new Tag(field_name : 'tag_name_1', field_value : '',
new Tag(field_name : 'tag_name_2', field_value : '',
new Tag(field_name : 'tag_name_3', field_value : ''
}])
function Line(data) {
var self = this;
self.tags = root.tags;
}
root.lines = ko.observableArray([]))
}
答案 0 :(得分:0)
Ko映射插件可用于克隆。
//Use this function as constructor function
function Tag(data) {
var self = this;
self.field_name = data.field_name;
self.field_value = data.field_value;
}
function Line(data) {
var self = this;
self.tags = ko.mapping.fromJS(root.tags); //mapping pluggin will make a copy of tags
self.remove = function (data) {
self.tags.remove(data);
}
self.add = function () {
self.tags.push(new Tag({
field_name: 'new tag_name',
field_value: ''
}));
}
}