我遇到了knockoutjs验证插件和映射插件的问题。
我有以下视图模型:
var AthleteViewModel = function (json) {
var self = this;
// Instantiate the TrainZones like that: The input field is empty and it looks
// like the property is not correctly bind but my Save() method shows "true"
self.TrainZones = ko.validatedObservable(new TrainZonesViewModel(json.TrainZones));
// Instantiate the TrainZones like that: The input field contains a value
// and my validation is running but the Save() method don't run because an error
// occurs that isValid() is not a function
// self.TrainZones = new TrainZonesViewModel(json.TrainZones);
self.Save = function () { alert(self.TrainZones.isValid()); };
};
var TrainZonesViewModel = function (json) {
var self = this;
ko.mapping.fromJS(json, {}, self);
self.RunningZone1Down.extend({ number: true });
self.RunningZone1Up.extend({ number: true });
};
现在我在我的视图中实例化AthleteViewModel
:
var viewModel = {};
$(function () {
viewModel = new AthleteViewModel(json);
ko.applyBindings(viewModel);
});
将属性绑定到输入字段:
<input type="text" data-bind="value: TrainZones.RunningZone1Down">
我的问题是,用行
self.TrainZones = ko.validatedObservable(new TrainZonesViewModel(json.TrainZones));
我有一个空输入字段,但self.TrainZones.isValid()
显示true
。
使用
行self.TrainZones = new TrainZonesViewModel(json.TrainZones);
属性绑定正确,并且此字段的验证也会运行,但isValid()
中没有方法self.TrainZones
。
如何解决此问题,合并两个解决方案并获得两种功能? ; - )