My web page uses this viewmodel for a master-detail scenario:
ko.extenders.myrequired = 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;
};
function PluginViewModel() {
var self = this;
self.name = ko.observable();
self.code = ko.observable();
}
function item() {
var self = this;
self.id = ko.observable();
self.listIndex = ko.observable();
self.value = ko.observable();
self.label = ko.observable();
self.tabPos = ko.observable();
self.plugins = ko.observableArray();
};
function TableViewModel() {
var self = this;
self.id = ko.observable();
self.name = ko.observable();
self.viewName = ko.observable().extend({ myrequired: "Please enter a view name" });
self.columns = ko.observableArray();
self.filteredColumns = ko.observableArray();
}
function SchemaViewModel() {
var self = this;
self.name = ko.observable();
self.tables = ko.observableArray();
// Table selected in left panel
self.selectedTable = ko.observable();
self.selectTable = function (p) {
self.selectedTable(p);
}
}
So when I click on a "<"li">" of selectedTable, knockoutjs binding show me other fields like a input text to write viewName field.
This is HTML code:
<div>
<ul class="list" data-bind="foreach: tables">
<li><a data-bind="text: name, click: $parent.selectTable"></a></li>
</ul>
</div>
<div>
<div id="editor-content">
<section id="viewNameSection">
<div data-bind="with: selectedTable">
<label>View name: </label>
<input id="txtViewName" class="inputs" data-bind="value: viewName, valueUpdate: 'input'" placeholder="eg. MyView" />
<span data-bind="visible: viewName.hasError, text: viewName.validationMessage"></span>
</div>
</section>
</div>
</div>
The problem is that no message is shown even if txtViewName is empty. It seems like extender not fire validation.
What I wrong?
EDIT: Funny thing is that Jfiddle with same code copy/paste works!
I really don't understand differences.
I found my error. 'viewName' field do not need initialization when populate tables. So, removing
myTable.viewName("")
it works.