0
votes

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:

enter image description here

Am i missing anything?

3

3 Answers

3
votes

{{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"}}>

0
votes

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.

0
votes

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; }),