我正在使用淘汰映射插件,之前我会设置一个像这样的订阅
self.selectedProduct.subscribe(function (name) {
}
but I'm unsure of how to do this in this format below. The message I get is
“缺失:属性ID后”
var viewModel = {
products: ko.mapping.fromJS([]),
productOptions: ko.mapping.fromJS([]),
productOptions.subscribe = function (name) {
alert('somthing change');
},
loadInitialData: function () {
ko.mapping.fromJS(serverData, viewModel.productOptions);
}
}
答案 0 :(得分:5)
如果要将视图模型定义为对象文字,则无法进行函数调用,就像进行内联操作一样。您必须在创建视图模型后执行此操作,或以不同方式创建视图模型。
如果你之后做了,那么它看起来像是:
var viewModel = {
products: ko.mapping.fromJS([]),
productOptions: ko.mapping.fromJS([]),
loadInitialData: function () {
ko.mapping.fromJS(serverData, viewModel.productOptions);
}
};
viewModel.productOptions.subscribe = function (name) {
alert('somthing change');
};
如果使用构造函数创建视图模型,那么它将如下所示:
var ViewModel = function() {
this.products = ko.mapping.fromJS([]);
this.productOptions = ko.mapping.fromJS([]);
this.productOptions.subscribe = function(name) {
alert("something change");
};
this.loadInitialData = function() {
ko.mapping.fromJS(serverData, this.productOptions);
};
};
var viewModel = new ViewModel();