我离使用 Ember 数据上传文件不远了。但我没有得到正确的值(value)约束。相关代码下方。
这是 App.js
App.LandcodeNewRoute = Ember.Route.extend({
model: function () {
return this.store.createRecord('landcode');
},
actions: {
saveLandcode: function () {
this.currentModel.save();
}
}
});
// REST & Model
App.ApplicationAdapter = DS.RESTAdapter.extend({
namespace: 'api'
});
App.Store = DS.Store.extend({
adapter: 'App.ApplicationAdapter'
});
App.Landcode = DS.Model.extend({
code: DS.attr('string'),
image: DS.attr('string')
});
// Views
App.UploadFile = Ember.TextField.extend({
tagName: 'input',
attributeBindings: ['name'],
type: 'file',
change: function (e) {
var reader, that;
that = this;
reader = new FileReader();
reader.onload = function (e) {
var fileToUpload = e.target.result;
console.log(e.target.result); // this spams the console with the image content
console.log(that.get('controller')); // output: Class {imageBinding: Binding,
that.get('controller').set(that.get('name'), fileToUpload);
};
return reader.readAsText(e.target.files[0]);
}
});
HTML
<script type="text/x-handlebars" data-template-name="landcode/new">
Code: {{input value=code}}<br />
Image: {{view App.UploadFile name="image" imageBinding="Landcode.image" }}
<button {{action 'saveLandcode'}}>Save</button>
</script>
如您在 HTML 部分所见,我尝试将图像内容绑定(bind)到 Landcode 模型属性图像。没有大写 L 也试过了。
我想我不能这样绑定(bind)图像,因为它是一个自定义 View 对象?而且我认为通常它会自动绑定(bind)。也许我只是把一些事情做了两次。
引用资料:
最佳答案
我将您的代码更新为以下内容:
App.LandcodeNewRoute = Ember.Route.extend({
model: function () {
return this.store.createRecord('landcode');
},
actions: {
saveLandcode: function () {
this.currentModel.save();
}
}
});
// REST & Model
App.ApplicationAdapter = DS.RESTAdapter.extend({
namespace: 'api'
});
App.Landcode = DS.Model.extend({
code: DS.attr('string'),
image: DS.attr('string')
});
// views
App.UploadFile = Ember.TextField.extend({
tagName: 'input',
attributeBindings: ['name'],
type: 'file',
file: null,
change: function (e) {
var reader = new FileReader(),
that = this;
reader.onload = function (e) {
var fileToUpload = e.target.result;
Ember.run(function() {
that.set('file', fileToUpload);
});
};
return reader.readAsDataURL(e.target.files[0]);
}
});
在 App.UploadFile
中,我没有直接引用 Controller ,而是设置了 file
属性。所以你可以绑定(bind)你的模型属性,使用 View :
{{view App.UploadFile name="image" file=image }}
Ember.run
用于您在测试应用程序时没有问题。
请查看那个 jsfiddle http://jsfiddle.net/marciojunior/LxEsF/
只需填写输入并单击保存按钮。您将在浏览器控制台中看到将发送到服务器的数据。
关于javascript - Ember.js 值与 HTML5 文件上传绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19909267/