我让 Ember 显示了一系列内容。
我希望用户上传一个文件并将内容列表更改为该文件中的内容。
HTML
<script type="text/x-handlebars" id="index">
<h2>List of things</h2>
<ul>
{{#each item in model}}
<li>{{item}}</li>
{{/each}}
</ul>
Change List of Things:
{{#view Ember.View}}
{{view App.FileUp}}
{{/view}}
</script>
Javascript
App = Ember.Application.create();
App.Router.map(function() {
// put your routes here
});
App.IndexRoute = Ember.Route.extend({
model: function() {
return ['red', 'yellow', 'blue'];
}
});
App.ApplicationController = Ember.Controller.extend({
actions: {
file_upload: function(data) {
alert("I want to change the model to: " + data);
}
}
});
App.FileUp= Ember.TextField.extend({
type: 'file',
change: function(evt) {
var input = evt.target;
if (input.files && input.files[0]) {
var that = this;
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
var c = App.ApplicationController.create();
c.send('file_upload', data);
}
reader.readAsText(input.files[0]);
}
},
});
在带有警报的行,我可以访问上传文件中的文本,并且我位于应用程序 Controller 中。如何更改模型以便页面列表反射(reflect)文本文件中的内容?
JS fiddle :http://jsfiddle.net/LJx9t/
如果此代码不是 Ember 惯用的代码,请随时更正。
最佳答案
作为组件,您应该使用 sendAction
将操作传递出组件。这允许组件被多次使用,并且不会将其绑定(bind)到上下文。
{{view App.FileUp uploadComplete='file_upload'}}
{{view App.FileUp uploadComplete='file_upload2'}}
然后在你的组件内部
change: function(evt) {
var input = evt.target,
self = this;
if (input.files && input.files[0]) {
var that = this;
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
self.sendAction('uploadComplete', data);
}
reader.readAsText(input.files[0]);
}
},
然后你的操作被发送到 Controller ,然后路由,然后沿着路由树向上直到它被处理。
创建一个索引 Controller 来处理它
App.IndexController = Ember.Controller.extend({
actions: {
file_upload: function(data) {
this.set('model', data.split('\n'));
},
file_upload2: function(data) {
alert(data);
}
}
});
关于javascript - Ember.js 文件上传以更改路线上的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20869616/