像这样的变量$root
仅在绑定中可用。
完成这项工作的一种方法是将对您的根视图模型的引用传递给您的 cartLine 构造函数。
您的 cartLine 最终看起来像:
var cartLine = function(data1, root) {
this.category = ko.observable(data1.category);
this.product = ko.observable(data1.product);
this.quantity = ko.observable(data1.quantity);
this.category.subscribe(function(newValue) {
if (newValue == "--Add New--") {
var name = prompt("Enter Table Name");
if (name == null) {
return false;
}
else {
root.categoryList.push(name);
}
}
});
};
然后,您只需this
在创建新的 cartLine 时作为视图模型的第二个参数传入。示例:http: //jsfiddle.net/rniemeyer/kzZSH/
否则,您可以照原样创建您的 cartLine,并在获得对新行的引用后从您的 viewModel 订阅。