为了解释我的问题,我应该提供一些介绍。
我在实际界面的My ViewModel中有大约5,6组属性, 这就是为什么简化这个例子的原因:
Album {
title: 'string'
artists: [{…}, {…}],
genres: [{…}, {…}]
}
艺术家/流派数组中的对象按结构相同:
item = {
id: 1,
title: 'string'
}
对于类似的属性组,我与其他函数类似:
self.AddArtist();
self.RemoveArtist(artist);
self.AddGenre();
self.RemoveGenre(genre);
Qustion:我是否只能使用AddItem(array)/RemoveItem(array, item)
之类的两个函数
处理ViewModel的所有属性组的操作?
答案 0 :(得分:1)
你可以使用这样的结构:
var Album = function() {
var self = this;
self.title = 'string';
self.groups = {
artists: ko.observableArray(),
genres: ko.observableArray()
};
self.addItem = function(groupName, item) {
self.groups[groupName].push(item);
};
self.removeItem = function(groupName, item) {
self.groups[groupName].remove(item);
};
}
用法:
album = new Album();
album.addItem('artists', 'test');