[英]How can I make a knockout "value" binding write-only so it doesn't try to read from it?
<input data-bind="value: fileName" type="file" multiple="">
<input data-bind="value: fileName" type="text" readonly="">
This works except I get:这有效,但我得到:
Uncaught InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.
because it tries to set the value of the file input when I only want to read it and write it to the text input.因为当我只想读取它并将其写入文本输入时,它会尝试设置文件输入的值。
http://jsfiddle.net/esk5akwj/2/ http://jsfiddle.net/esk5akwj/2/
Since the file chooser value can only be set by using the file chooser, and must start as the empty string, you need a custom binding handler that wraps the value
binding and on init sets the bound value to the empty string:由于文件选择器值只能使用文件选择器设置,并且必须以空字符串开头,因此您需要一个自定义绑定处理程序来包装
value
绑定,并在 init 上将绑定值设置为空字符串:
ko.bindingHandlers.resetValue = { init: function(element, valueAccessor, allBindingsAccessor, data, context) { valueAccessor()(''); ko.bindingHandlers.value.init(element, valueAccessor, allBindingsAccessor, data, context); }, update: function(element, valueAccessor, allBindingsAccessor, data, context) { ko.bindingHandlers.value.update(element, valueAccessor, allBindingsAccessor, data, context); } }; ko.applyBindings({ fileName: ko.observable(), c: ko.observable() });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <input data-bind="checked: c" type="checkbox">Check me, choose a file, uncheck me, check me, choose a file. <!-- ko if: c --> <input data-bind="resetValue: fileName" type="file" multiple=""> <input data-bind="value: fileName" type="text" readonly> <!-- /ko -->
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.