ember.js - 选择文件后的操作
问题描述
我几乎是第一次在 ember(和一般的 js)中工作。
这是场景:有一个“选择文件”按钮。标准文件选择按钮已被隐藏并替换为自定义按钮。用户单击该按钮,出现文件选择窗口,用户选择他们的文件,然后单击“确定”。因为默认按钮已被隐藏,所以我需要向用户表明已选择了一个文件。我想显示一条消息来表明这一点。
在template.hbs
我有类似的东西
<button class="outline-only inline-block" id="my_file_button" {{action 'clickButton' 'my_file'}}>
{{fa-icon icon="mouse-pointer"}} Choose file
</button>
<input type="file" id="my_file" name="my_file"> <!-- this is set to display: none in css file -->
{{#if my_file_button_clicked}}
{{fa-icon icon="check-circle"}} File selected
{{/if}}
在component.js
我定义为的一部分actions
:
clickButton(button) {
let self = this;
jquery('#'+button).click();
self.set(button+'_button_clicked', true);
}
这样做的目的是在用户单击“选择文件”按钮时立即显示“文件选择”消息,无论他们是完成文件选择还是单击“取消”。我怎样才能使它在完成、成功的选择之前不会显示消息?
解决方案
您应该将操作绑定到文件输入的change
事件。在 ember.js 你这样做是这样的:
<input type="file" id="my_file" name="my_file" onchange={{action 'fileChanged'}}>
事件作为参数传递给动作。它包含通过FileList对所选文件的引用。您可以使用它来检查用户是否选择了文件。如果用户选择了一个文件,您可以将它的引用存储在一个变量中。原始操作如下所示:
Component.extends({
filesSelected: null,
actions: {
fileChanged(event) {
let files = event.target.files;
this.set('filesSelected', files);
}
}
});
仅当已选择文件时,您才可以使用该变量显示图标:
{{#if filesSelected.length}}
{{fa-icon icon="check-circle"}} File selected
{{/if}}
请注意,已经有一些 Ember 插件提供了您尝试实现的功能。我建议查看 Ember Observer 上的文件上传类别:https ://www.emberobserver.com/categories/file-upload
推荐阅读
- javascript - 从帖子 URL 获取 facebook 直接图像
- ios - ARKIT:如何像 GiPHY World 应用一样在半空中移动物体
- kubernetes - Kubernetes GKE - 如何通过特定网关路由流量
- spring-security - 我是否应该使用 ESAPI,是否有替代品?
- quickfix - QuickFIXn - 现有连接被远程主机强行关闭
- c# - ASP.net Gridview 自动更新
- javascript - 显示搜索字段占位符文本
- c++ - 如何通过 C++ 中的 system() 将视频文件拆分为多个部分
- ios - 我正在尝试计算iOS中两次(HH:MM:SS)之间的差异
- facebook-graph-api - 以编程方式访问在 Faceboob 页面中分享帖子的人员列表