1
我花了兩天時間查看可能的答案,並嘗試瞭解所有內容以瞭解可能的工作方式。所以如果我忽略了一些東西,請原諒我。這是場景。敲除驗證,映射和動態表格
假設我導航到/#/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()視圖模型,所以驗證不起作用。
如果我把一個靜態字段,驗證工作得很好。
我已經嘗試了很多不同的東西,但似乎沒有任何工作。希望有人能幫助解決一些問題。
謝謝。