让我们假设我有一个模态,其中在由 jquery-file-upload 制成的模态体中有一个 FileUpload 组件。
该组件在视图模型中有一个名为“Upload”的方法,该方法会遍历选定的文件并上传它们。
现在,当我按下模式上的“上传”按钮时,我想上传文件。实现这一目标的最佳和最干净的方法是什么?
我现在的代码是这样的(请注意,这只是一些快速原型代码):
<div data-bind="component:{name:'FileUpload', params:FileUpload}"></div>
<button data-bind="click:test">test</button>
@section Scripts
@Scripts.Render("~/scripts/global/fileUpload")
@Styles.Render("~/Content/css/fileUploadCSS")
<script type="text/javascript">
var model = function () {
var self = this;
self.FileUpload = {
url: 'test',
onFailed: function (e, data) {
console.log('failed')
}
};
self.test = function () { console.debug(self.FileUpload) }
}
ko.applyBindings(new model(), document.getElementById("main"))
</script>
End Section
以及组件本身:
ko.components.register('FileUpload', {
viewModel: function(params) {
var self = this;
self.files = ko.observableArray();
self.template = params.template;
self.multiple = params.multiple || false;
self.progress = ko.observable(0);
var acceptFileTypes = params.acceptFileTypes || /(\.|\/)(gif|jpe?g|png|pdf|eps|tiff|cdr|PDF|CDR|JPG|EPS|TIFF|pptx|docx|xlsx|ppt|doc|xls)$/i;
var maxFileSize = params.maxFileSize || 104857600;
self.Upload = function() {
$.each(self.files(), function(index, file) {
file.submit();
});
};
self.options = {
type: params.type || "POST",
dataType: params.dataType || "json",
formData: params.formData || {},
url: RTC.SiteUrl() + params.url,
sequentialUploads: params.sequentialUploads || true,
dropzone: params.dropzone||$(this),
autoUpload: params.autoUpload || false,
forceIframeTransport: true,
limitMultiFileUploadSize: params.maxFileSize || maxFileSize,
maxFileSize: params.maxFileSize || maxFileSize,
done: function (e, data) {
if (params.onUploaded)
params.onUploaded(e, data);
RTC.Progressor.Done();
},
fail: function (e, data) {
if (params.onFailed)
params.onFailed(e, data);
RTC.Progressor.Done();
},
start: function(e,data) {
RTC.Progressor.Start();
},
progressall: function(e, data) {
RTC.Progressor.Set(data.loaded / data.total*100);
},
add: function (e, data) {
//if (data.originalFiles[0]['size'] > maxFileSize) {
// RTC.addAlert(RTC.translate(220, "[220: File is invalid]"), "alert-danger", RTC.translate(193, "[193: An error occurred]"));
//} else if (!acceptFileTypes.test(data.originalFiles[0]['name'])) {
// RTC.addAlert(RTC.translate(198, "[198: Wrong file format]"), "alert-danger", RTC.translate(193, "[193: An error occurred]"));
//} else {
self.progress(0);
if (!self.multiple)
self.files.removeAll();
self.files.push(data);
// }
}
};
},
template: { element: "fileUploadTemplate" }
});
ko.bindingHandlers.fileUpload = {
update: function (element, valueAccessor) {
var options = valueAccessor() || {};
//initialize
//.fileInput || $(this),
$(element).fileupload(options);
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
// This will be called when the element is removed by Knockout or
// if some other part of your code calls ko.removeNode(element)
$(element)("destroy");
});
}
};