Ember component: property X was changed inside the didInsertElement hook deflection, where should the set go?

Full disclaimer DEPRECATION: A property of <orders-app@view:test-holder::ember3010> was modified inside the didInsertElement hook. You should never change properties on components, services or models during didInsertElement because it causes significant performance degradation.

To keep things simple, let's say we have a component with an input field and we want to set the date of the text field to today and a few days numberOfDays

. So if today is January 3rd 2015 and numberOfDays=2

then the textbox value should be 01/05/2015 (assuming we want to format DD-MM-YYYY). So our setup could be:

date-shower.hbs

{{input type="text" value=dateInput}}

      

components / data-shower.js

export default Ember.Component.extend({
  didInsertElement: function() {
    var numberOfDays = this.get('numberOfDays');
    var dayToUse = new Date(); // today
    dayToUse.setDate(dayToUse.getDate() + numberOfDays);

    this.set('dateInput', moment(nextDay).format('DD-MM-YYYY'));
  }
});

      

We can then use this with something like

{{date-shower numberOfDays=2}}

      

When it makes sense for a component to compute a default value for one, that is the properties themselves, based on the properties passed to it, which hook should I use instead of didInsertElement to prevent the failure message?

+3


source to share


2 answers


You will need to use the computed property to handle the settings and get dateInput

it, something like the line:

dateInputHandler: computed('numberOfDays', {
  set(key, val) {
    if (val) {
      this.set('dateInput', val);
    } else {
      this.set('dateInput', null);
    }
    return val;
  },
  get() {
    let dateInput = this.get('dateInput');
    if (!dateInput) {
      let numberOfDays = this.get('numberOfDays');
      let dayToUse = new Date(); // today
      dateInput = dayToUse.setDate(dayToUse.getDate() + numberOfDays);
      this.set('dateInput', dateInput);
    }
    return dateInput;
  }
})

      



In your template, you must use value=dateInputHandler

+3


source


I would make a dateInput

computed property on the component and let Ember handle the property for you to make sure it happens at the right time:

import Ember from 'ember';

const { Component, computed } = Ember;

export default Component.extend({
  didInsertElement() {
    // nothing needed in here
  },

  dateInput: computed('numberOfDays', function() {
    let numberOfDays = this.get('numberOfDays');
    let dayToUse = new Date(); // today

    dayToUse.setDate(dayToUse.getDate() + numberOfDays);

    return moment(nextDay).format('DD-MM-YYYY');
  })
});

      



This way your value dateInput

will be computed as soon as it numberOfDays

becomes available.

+5


source







All Articles