Reputation: 4681
Hi i have a simple code that updates a component's property value e.g. with a button click, and based on that value i need to update the value
of the input text, like so:
template:
{{input value=myValue type="text" }}
<button {{action "update"}}>update</button>
component.js:
myValue: Ember.computed("product", function(){
if(this.get("product")) {
return this.get("product");
}
}),
actions:
update(){ this.set('product', 'new value')}
But although, the "product" property is updated , the input value stays the same,
computed
function is not triggered.
<input>
after button click, should be:Am i missing anything?
Upvotes: 1
Views: 1992
Reputation: 4681
So,
what i need here is a 2-way data bind, because i update myValue
from :
1. input text
2. from 'product'
My computed method needs slightly refactor, to add a getter
& setter
, like so:
myValue: Ember.computed("product", function(){
get(key){
return this.get("product");
},
set(key, value){
this.set(product', value);
return value;
}),
Upvotes: 0
Reputation: 6328
{{input}}
template helper does a two-way binding. For good reasons this is considered a bad practice these days. You face one of this issues.
If input value changes {{input}}
template helper sets the new value on myValue
. This overrides your computed property cause that one does not implement a setter. Afterwards your input is not bound to product
anymore. Therefor changing product
will not update the input.
You have different ways to address this issue. One option would be to implement a setter in myValue
computed property or simply use a macro like computed.alias
. But I would recommend to drop the input helper and it's two-way binding. Instead set the value explicitly on change: <input value={{myValue}} onchange={{mut "product" value="target.value"}}>
Upvotes: 4
Reputation: 11
If you are wanting to only update a value on the button press, I suggest using an action on the button.
template.hbs
<button {{action "updateProduct" product}}>update</button>
component.js
actions: {
updateProduct(product) {
this.set('product', product);
}
}
https://guides.emberjs.com/release/templates/actions/#toc_action-parameters
Let me know if I'm misunderstanding you here.
Upvotes: 0