user2517182
user2517182

Reputation: 1299

Ember this.set in component

I seem to be doing something wrong with the init property of an Ember component.

My code looks something like this.

import Ember from 'ember';

export default Ember.Component.extend({
  init(){
    this._super(...arguments);
    this.set('initial_value', this.get('value'));
  },

  change(e){
    console.log('value should be reset to ' + this.get('initial_value')) //This prints the initial value correctly.
    this.set('value', this.get('initial_value')); // this line does not update value.
    //this.set('value', 'hello'); //this line does update value.   
  }
});

Why can I update value with a string literal but not with this.get('initial_value')?

And I tried this code, swapping out init for every function in the lifecycle of a component. I did this because I thought it had some to do with the rendering; kind of still do.

Here is the twiddle.

Upvotes: 0

Views: 2066

Answers (2)

Vignesh Raja
Vignesh Raja

Reputation: 8761

Since you have used, <input type="text" value={{value}}>, its one-way binding. i.e., on changing value in the component the change will get reflected in the input box, but changing the value in the input box will not change the value of the variable value in the component.

In Ember, DOM gets updated only when the value of the variable in the component changes. In my-component.js, the value of variable value is not changing. It just contains the string literal initial value.

For instance, this.set('value', Math.random()); this will work as the value of the variable value changes.

Why can I update value with a string literal but not with this.get('initial_value')?

It can be done only once as the value changes only 1 time. (While changing the value to string during first time)

To achieve your case, You can use {{input value=value}} which implements two-way binding. When editing your input box, the value of the variable value changes.

On focussing out, this.set('value',this.get('initial_value')) will set the initial value as required.

Twiddle for reference

Upvotes: 1

Ember Freak
Ember Freak

Reputation: 12872

You can just include {{input value=value}} in my-component.hbs file, when you change the input it will call change function in input helper which will call change function of your component which will reset it to initial_value.

Upvotes: 0

Related Questions