对于任何感兴趣的人,您可以使用以下自定义绑定,它允许将文件输入元素绑定到包含File的淘汰赛 observable 。
它处理将 observable 设置为所选文件(由 @nemesv 回答),以及在 observable 设置为 null 时清除输入元素(请参阅此答案):
ko.bindingHandlers.fileUpload = {
init: function (element, valueAccessor) {
$(element).change(function () {
valueAccessor()(element.files[0]);
});
},
update: function (element, valueAccessor) {
if (ko.unwrap(valueAccessor()) === null) {
$(element).wrap('<form>').closest('form').get(0).reset();
$(element).unwrap();
}
}
};
例子:
function Example() {
var self = this;
self.uploadFile = ko.observable(null);
self.uploadName = ko.computed(function() {
return !!self.uploadFile() ? self.uploadFile().name : '-';
});
self.clear = function() {
self.uploadFile(null);
};
};
ko.bindingHandlers.fileUpload = {
init: function(element, valueAccessor) {
$(element).change(function() {
valueAccessor()(element.files[0]);
});
},
update: function(element, valueAccessor) {
if (ko.unwrap(valueAccessor()) === null) {
$(element).wrap('<form>').closest('form').get(0).reset();
$(element).unwrap();
}
}
};
ko.applyBindings(new Example());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="file" data-bind="fileUpload: uploadFile">
<br/>
<br/>Selected file name: <span data-bind="text: uploadName"></span>
<br/>
<button data-bind="click: clear">Clear input</button>