【发布时间】:2017-09-05 11:00:39
【问题描述】:
我有以下 ViewModel:
var Order = function(data) {
this.fruits = ko.observableArray(ko.utils.arrayMap(data.Fruis, function(item) { return item; }));
this.vegetables = ko.observableArray(ko.utils.arrayMap(data.Vegetables, function(item) { return item; }));
};
我需要定义一些绑定到具体实例的子属性和子可观察对象,以及水果和蔬菜的一些常用方法,:
var Items = function(data, type) {
var self = this;
self.type = type;
self.choice = ko.observable(-1);
self.choice.select = ko.computed(function(){
var id = self.choice();
// do stuff
});
self.choice.remove = function() {
var id = self.choice.peek();
// do stuff
};
self.add = function(code) {
//do stuff
self.choice(id);
};
};
这是绑定包含我的一组方法和子可观察对象的函数的正确方法,以便我可以使用如下方法:
orderViewModel.fruits.add("apples");
orderViewModel.fruits.add("bananas");
orderViewModel.fruits.choice(0);
orderViewModel.fruits.choice.remove();
console.log(ko.tpJSON(orderViewModel));
// prints: {fruits: [bananas], vegetables: []};
我认为没有必要使用 extenders,因为属性和方法不是通用的,并且不需要对所有 observables 都是通用的。
我尝试从我的 Item 函数返回一个可观察数组,但我无法让它工作,因为子属性和子可观察对象已经丢失。如何将Items 绑定到我的可观察数组?
【问题讨论】: