1
votes

Having a hard time figuring out why controller properties added in init() are added as 'undefined' rather than with default values. I guess you're supposed to define in init() to avoid "leaking state"? I think I am missing something fundamental here.

When a controller property like an empty array is specified right on the controller it's added as 'Array[0]', which then allows you to pushObject stuff into it. When added in init() they are added as 'undefined' so pushObject fails.

See demo on this twiddle and/or the code below:

import Ember from 'ember';

export default Ember.Controller.extend({

    queryParams: ['q','sort_method','search_type','filter1','filter2'],

    init(){
        this._super(...arguments);

        Ember.set(this, 'q', null);
        Ember.set(this, 'sort_method', 'relevance'); // <-- sets default value to 'undefined'
        Ember.set(this, 'filter1', []); // <-- sets default value to 'undefined'
    },

  filter2: [], // <-- sets default values properly but will it cause state issues?
  search_type: 'bar'

});

Basically, I'm wanting to figure out how to declare my list of query params in ONE place (like in config file), rather than 3 places (route, controller queryParams array, and to the controller itself)

I created a twiddle to illustrate what I mean.

1

1 Answers

0
votes

why controller properties added in init() are added as 'undefined'

If you dig deep into ember sources, you will find a lot of code in Ember.Route that "prepare" query parameters to work (for example, you may try to analyze this code). I guess that answer to this question is somewhere in route's code (probably route initialize properties before/after controller's init is called or something like that).

Basically, I'm wanting to figure out how to declare my list of query params in ONE place (like in config file), rather than 3 places (route, controller queryParams array, and to the controller itself)

You can declare parameters in environment.js. Then, in controller import it and pass to Ember.Controller.extend

import ENV from 'project-name/config/environment';

export default Ember.Controller.extend(Ember.$.extend({}, ENV.myDefaults.controller, {
  actions: {
    addFilter: function(key, value) {
      alert(`adding "${value.toString()}" to controller property '${key}'`);
      console.log("DUMP OF EMBER 'this':", this);
      this[key].pushObject(value.toString());
    }     
  } 
}));

See twiddle for details