1

我的网页将此视图模型用于主从场景:

   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);
    }
}

因此,当我单击 selectedTable 的 "<"li">" 时,knockoutjs 绑定会向我显示其他字段,例如输入文本以写入 viewName 字段。

这是 HTML 代码:

<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>

问题是即使 txtViewName 为空,也不会显示任何消息。似乎扩展器不是火验证。

我错了什么?

编辑: 有趣的是Jfiddle具有相同的代码复制/粘贴工作!

我真的不明白差异。

4

2 回答 2

0

我相信应该是

//define a function to do validation
function validate(newValue) {
    var isEmptyOrNull= typeof newValue === 'undefined' || !newvalue || newValue.length === 0;
    target.hasError(isEmptyOrNull);
    target.validationMessage( isEmptyOrNull ? 
                                overrideMessage || "This field is required"
                             :
                                "");
}

作为旁注,您可能需要考虑将validationMessage 设为计算值而不是可观察值。

于 2014-03-28T10:49:00.713 回答
0

我发现了我的错误。填充表格时,“viewName”字段不需要初始化。所以,删除

myTable.viewName("") 

有用。

于 2014-03-31T07:59:31.137 回答