Javascript 如何在emberjs上使用单向绑定? 我开始玩弄余烬,但有一件事我无法总结我的观点,那就是如何使用单向绑定,考虑下面的代码:
HTMLJavascript 如何在emberjs上使用单向绑定? 我开始玩弄余烬,但有一件事我无法总结我的观点,那就是如何使用单向绑定,考虑下面的代码:,javascript,jquery,data-binding,ember.js,handlebars.js,Javascript,Jquery,Data Binding,Ember.js,Handlebars.js,HTML <script type="text/x-handlebars"> <h1>Some App</h1> <p> My Name is: {{name}} </p> <form {{action 'updateName' on="submit"}}> {{view Ember.TextField valueBinding="name"}}
<script type="text/x-handlebars">
<h1>Some App</h1>
<p>
My Name is: {{name}}
</p>
<form {{action 'updateName' on="submit"}}>
{{view Ember.TextField valueBinding="name"}}
<input type="submit" value="Save">
</form>
</script>
默认情况下,Ember.TextField
的值将绑定到我的模型,反之亦然,这意味着当我键入文本时,模型和视图将实时更新,但是我试图做的是将模型绑定到TextField(因此将显示初始名称),但仅在提交表单时更新模型。有没有简单的方法
提前谢谢
编辑:仅供参考,我更新了我的小提琴以使用
Ember.Binding。单向
我认为最终结果比@c4p更清晰回答:但是我不确定是否使用$('#用户名')。val()
获取字段值是正确的方法。你可以使用观察者,控制器上的一个中间绑定变量,以及控制器上的一个事件处理程序,以完成所需操作
当namedichange()
观察者触发时,将更新控制器的nameocontroller
属性,确保nameocontroller
属性将初始化为模型的name
属性,并反映对name
的任何未来更改。将此中间属性绑定到文本字段
,将名称
属性与即时键入更改隔离,并仅在单击按钮时使用控制器上的事件读取和设置名称
属性
模板:
{{view Ember.TextField valueBinding="nameOnController"}}
JS:
通过单击
设置新名称
按钮,可以检查对名称
属性的更改是否仍反映在文本框中。这是一个更新的解决方案
我有一个类似的问题,我需要一个单向绑定,但在一些操作中,我需要最新的值。我还需要当前编辑的值。
下面是我的概念证明--
把手:
<h1>Some App</h1>
<p>My Name is: {{model.name}}</p>
<p>current value: {{currentName}}</p>
{{one-way-field id="user-name" source=model.name action='handleNameChange'}}
<button {{action 'updateName'}}>Save</button>
App = Ember.Application.create();
App.ApplicationController = Em.Controller.extend({
model: {
name: 'John Doe'
},
actions: {
updateName: function() {
this.set('model.name', this.get('currentName'));
},
handleNameChange: function(newValue) {
this.set('currentName', newValue);
},
}
});
App.OneWayFieldComponent = Ember.TextField.extend({
valueBinding: Ember.Binding.oneWay('source'),
onValueChange: function() {
this.sendAction('action', this.get('value'));
}.observes('value'),
});
这可能是你想要的吗?的确,但是我不知道如何实现它,因此我的问题嘿,伙计,谢谢你的编辑。我一直在寻找一个不使用可观察变量的解决方案:)-你应该回答你自己的问题。谢谢,看起来不使用
Ember.Binding.one-way是可能的,然后作为参考,我更新了我的fiddle使用Ember.Binding.one-way
我认为最终的结果要干净得多:但是我不确定使用$(“#用户名”).val()
获取字段值是否正确。
<h1>Some App</h1>
<p>My Name is: {{model.name}}</p>
<p>current value: {{currentName}}</p>
{{one-way-field id="user-name" source=model.name action='handleNameChange'}}
<button {{action 'updateName'}}>Save</button>
App = Ember.Application.create();
App.ApplicationController = Em.Controller.extend({
model: {
name: 'John Doe'
},
actions: {
updateName: function() {
this.set('model.name', this.get('currentName'));
},
handleNameChange: function(newValue) {
this.set('currentName', newValue);
},
}
});
App.OneWayFieldComponent = Ember.TextField.extend({
valueBinding: Ember.Binding.oneWay('source'),
onValueChange: function() {
this.sendAction('action', this.get('value'));
}.observes('value'),
});