1

我有一个增值税注册号字段。我为它分配了 JQuery.InputMask 库中的掩码;

$("input.vatreg").inputmask("999-9999-99");

在淘汰赛中,我使用以下编辑模板;

<script id="editTmpl" type="text/html">
    <tr>
        <td><input data-bind="value: Name, hasFocus: addNew" /></td>
        <td><input data-bind="value: VatRegistrationNumber" class="vatreg" /></td>
        <td>
            <button data-bind="click: $root.acceptItemEdit" style="margin-right:10px;">Accept and Save</button>
            <button data-bind="click: $root.cancelItemEdit">Cancel</button>
        </td>
    </tr>
</script>

如您所见,这使用了 vatreg 类,我的期望是该字段会启用掩码,但事实并非如此。我该如何解决?

4

1 回答 1

1

认为您可能需要自定义绑定。我做了一个。运行下面的代码段。顶部输入框是自定义绑定。下面的跨度是可观察的值。最后一个输入框是测试更新 observable 并确保更新输入掩码。

ko.bindingHandlers.inputmask = {
  init: function(element, valueAccessor, allBindingsAccessor) {
    $(element).inputmask("999-9999-99", {
      "oncomplete": function() {
        valueAccessor()($(element).val());
      }
    });

    //handle disposal (if KO removes by the template binding)
    ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
      $(element).inputmask("destroy");
    });

  },
  //update the control when the view model changes
  update: function(element, valueAccessor, allBindingsAccessor) {
    var value = ko.utils.unwrapObservable(valueAccessor());
    $(element).val(valueAccessor()());
  }
};



function model() {
  var self = this;
  this.VatRegistrationNumber = ko.observable('888-8888-88');

}

var mymodel = new model();

$(document).ready(function() {
  ko.applyBindings(mymodel);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js"></script>

<p>
input mask:
<input data-bind="inputmask: VatRegistrationNumber" class="vatreg" />
</p>
</br>
<p>
  input mask value: <span data-bind="text: VatRegistrationNumber"></span>
</p>

<br>
update the value <input data-bind="value: VatRegistrationNumber" class="vatreg" />

于 2017-05-24T00:35:59.190 回答