使用Ember.js进行手动格式数据保存的正确方法是什么? [英] What's the right way of doing manual form data saving with Ember.js?
问题描述
我正在Ember.js中创建一个手动保存的表单,其中包含适量的字段(我们说20个)(不使用实时绑定),而且目前为止,正确的方法/最佳做法感到困惑。我发现了以下方法:
I'm trying to create a manually saved form with a moderate number of fields (let's say 20) in Ember.js (not using live bindings) and so far am confused about the correct way / best practice for doing so. I've found the following methods:
http://www.solitr.com/blog/2012/06/ember-input-field-with-save-button/
https:// stackoverflow.com/a/16473186/1248965
所有上述方法在某种程度上似乎都是黑客;他们或者扩展文本字段或使用每场观察者,要求您列出每个观察者。还有其他一些方法吗?像未绑定的帮手,但允许自动模型更新魔术/验证(通过ember数据)在某些动作(如unbound-until或条件绑定或某些东西)?我已经经历了所有的文档,SO,github问题,Ember论坛和上面的链接,仍然觉得我一定错过了一些。
All of the above methods seem hacky to a degree; they either extend the text field or use a per-field observer, requiring you to list out each one. Is there some other way? Something like the 'unbound' helper, but allowing the auto-model updating magic / validation (via ember-data) on some action (like an 'unbound-until' or 'conditional-bind' or something)? I've gone through all the docs, SO, the github issues, the Ember forum, and the links above, and still feel like I must have missed something.
基本上一个方法来说做一切你通常绑定的表单/字段,但只是在一定的行动,而不是实时。
Basically, a way to say "do everything you would do with a normally bound form/fields, but only on a certain action, rather than in real time."
推荐答案
您想要的是一个缓冲代理,您可以暂时将所有更改存储到模型中(您可以使用 setUnkownProperty
捕获这些更改)代理对象。一旦您对变更感到满意,您可以将所有代理数据复制到实际对象中(刷新数据)。
What you want is a "Buffered Proxy", where you temporarily store all changes to the model (you can catch those using setUnkownProperty
) in a proxy object. Once you are happy with the changes, you'd copy all of the proxy data over into the actual object ("flush the data").
App.Heisenberg = {
firstName: 'Walter',
lastName: 'White',
};
App.IndexRoute = Ember.Route.extend({
model: function() {
return App.Heisenberg;
},
setupController: function(controller, model) {
controller.set('content', model);
}
});
App.IndexController = Ember.ObjectController.extend({
proxy: {},
setUnknownProperty: function(key, value) {
console.log("Set the unknown property: " + key + " to: " + value);
this.proxy[key] = value;
console.log(this.proxy);
},
flush: function() {
for(var key in this.proxy)
this.set('model.'+key, this.proxy[key]);
}
});
模板:
<script type="text/x-handlebars" data-template-name="index">
Saved Name: {{firstName}} {{lastName}}<br />
<br />
<form {{ action "saveEdit" on="submit" }}>
First Name: {{input type="text" valueBinding="firstName"}}<br />
Last Name: {{input type="text" valueBinding="lastName"}}<br />
<br />
<button {{ action "flush" }}>Flush</button>
</form>
</script>
这将为一个不错的控制器Mixin。
This would make for a nice controller Mixin.
请参见此jsBin 以了解实例。
这篇关于使用Ember.js进行手动格式数据保存的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!