-1

使用 Knockout 库,我编写了一个 ViewModel(主要基于他们的在线指导),它进行了一些验证。一切都很完美,除了...

1)一旦我的对话框启动,验证立即调用

2)我想将验证绑定到对话框按钮而不是输入框,并且仅在用户单击“添加新帐户”按钮时触发。

下面是我的 JSFiddle 的链接。感谢您提供的任何指导。

http://jsfiddle.net/9PV7X/

HTML

<a href="#" id="createAccount">Create New Account</a> 

<div id="newAccount" title="New Account">
<p> 
    <span class="ui-state-highlight" data-bind='visible: accountName.hasError, text: accountName.validationMessage'> </span>
</p>
  <form>
  <fieldset>
      <label for="name">Enter Account Name:</label><br />
    <input type="text" id="accountName" data-bind='value: accountName, valueUpdate: "afterkeydown"'  />
  </fieldset>
  </form>
</div>

视图模型

$("#newAccount").dialog({
    autoOpen: false,
    width: 450,
    height: 300,
    modal: true,
    buttons: {
        "Add New Account": function () {
            // post data
            $(this).dialog("close"); 
        },
        Cancel: function () {
            $(this).dialog("close");
        }
    }
});

$("#createAccount")
    .click(function () {
        $("#newAccount").dialog("open");
    });

    ko.extenders.required = function(target, overrideMessage) {
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    function validate(newValue) {
       target.hasError(newValue ? false : true);
       target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
    }

    validate(target());
    target.subscribe(validate); 
    return target;
};

function ViewModel(account) {
    this.accountName = ko.observable(account).extend({ required: "An account name is required" });
}

ko.applyBindings(new ViewModel());

干杯,

克劳德

4

1 回答 1

1

您需要对代码进行两次修改:

  1. 为了防止在对话框启动后立即调用验证,只需删除或注释此行validate(target());。这只是初步验证。
  2. 打开对话框时应用模型绑定,如果对话框未打开,则不需要应用它:

像这样

open:function(){
    ko.applyBindings(new ViewModel());
}

请检查这个工作演示

于 2013-07-17T15:04:45.697 回答