在我决定在我的视图模型中添加一些扩展器之前,一切都很好。
我只是从knockout docs进行复制粘贴。我需要的是强制某些字段为数字(在本例中我使用了所需的扩展名)。
问题是当我更改扩展属性时,我的所有模型都会重新启动。我怎么知道的?因为所有字段都获得初始值。
var ProductToAddVM = function () {
var self = this;
self.style = ko.observable().extend({ required: "Please enter a first name" });
self.children = ko.computed(function () { return "something computed" }
};
var PurchaseVM = function () {
var self = this;
self.newInvoiceNewProduct = ko.observable(new ProductToAddVM());
};
ko.extenders.required = function (target, overrideMessage) {
//add some sub-observables to our observable
target.hasError = ko.observable();
target.validationMessage = ko.observable();
//define a function to do validation
function validate(newValue) {
target.hasError(newValue ? false : true);
target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
}
//initial validation
validate(target());
//validate whenever the value changes
target.subscribe(validate);
//return the original observable
return target;
};
$(document).ready(function() {
ko.applyBindings(PurchaseVM);
});
我错过了什么?
答案 0 :(得分:1)
在这里查看语法错误 -
var ProductToAddVM = function () {
var self = this;
self.style = ko.observable().extend({ required: "Please enter a first name" });
self.children = ko.computed(function () { return "something computed" });
}
还有其他人......