我花了两天时间寻找可能的答案,并尝试了几乎所有的东西,看看什么可能有效。所以,如果我忽略了什么,请原谅我。这是场景。
假设我导航到某个 url,/#/register/:session
并且这条路由触发了我希望用户填写的字段的 JSON 请求,以便注册此会话。像这样的东西:
fieldsMapping = { "include": ["fields"] }
ko.mapping.fromJS(data, fieldsMapping, self.attendee.registration.registrationFields);
响应只是一个 JSON 对象,我将其映射到名为 registrationFields() 的视图模型。JSON 看起来像这样:
"fields": [
{ "field": "firstName", "required": true, "maxSize": 128 },
{ "field": "lastName", "required": true, "maxSize": 128 },
{ "field": "email", "required": true, "maxSize": 128 }
]
下一步是为响应中的任何字段生成 HTML。
<div class="registration-fields" data-bind="foreach: webapp.attendee.registration.registrationFields.fields(), registrationFieldsLayout: true">
<label data-bind="text: message('registration.registrant.field.' + field()), attr: { for: '#' + field() }"></label>
<!-- ko if: field() === "firstName" || field() === "lastName" -->
<input type="text" data-bind="attr: { id: '#' + field(), value: $parent.firstName, 'data-validate': (required()) ? true : false }">
<!-- /ko -->
<!-- ko if: field() === "email" -->
<input type="email" data-bind="attr: { id: '#' + field(), value: $parent.email, 'data-validate': (required()) ? true : false }">
<!-- /ko -->
</div>
对于$parent
变量,我附加了另一个视图模型来保存名为 RegistrationForm() 的表单数据。我在表单标签中这样做:
<form method="post" data-bind="with: webapp.attendee.registration.registrationForm">
registrationForm() 视图模型如下所示:
function (ko, validationRules) {
return function RegistrationForm () {
var self = this;
validationRules();
self.firstName = ko.observable().extend({ required: true });
self.lastName = ko.observable().extend({ required: true });
self.email = ko.observable().extend({ required: true, email: true });
self.submit = function () {
if (self.errors().length === 0) {
console.log("hurrah");
} else {
console.log("errors should be shown");
self.errors.showAllMessages();
}
}
self.errors = ko.validation.group(self);
}
}
现在,我所有的视图模型都加载了 requirejs,这很棒。但是发生的情况是,我的字段在呈现后没有附加到 RegistrationForm() 视图模型,因此验证不起作用。
如果我输入一个静态字段,验证就可以了。
我尝试了很多不同的东西,但似乎没有任何效果。希望有人可以帮助阐明一些光。
谢谢。