1
votes

Is there an easy way to add controller properties directly from a javascript object?

As opposed to having to manually specify each and every query param I want to use in 3 places: queryParams, QP controller properties, and route queryParams[key].refreshModel = true...I just want to maintain this stuff in ONE object and update it to all those places:

const cfg = {
    defaultQueryParams: {
        q: null,
        paging: '18',
        search_sort: 'relevance',
        search_title: null,
        search_page: null,
        filter_breadcrumb: [],
        filter_price: [],
        filter_size_apparel: [], 
        filter_color: [] 
    }
};

In the controller I tried:

export default Ember.Controller.extend({
    queryParams: Object.keys(cfg.defaultQueryParams), // works great!

    init() {  
        this._super(...arguments);
        this.addObject(cfg.defaultQueryParams); // doesn't work: "this.addObjects is not a function"
        // same with addObjects, setObjects
    },
    ...
});

I also tried iterating over the JS object and using the setter. It works for strings, but not for the empty arrays:

    for (let [key, value] of Object.entries(cfg.defaultQueryParams)) {  
        this.set(key, value);
    }

The arrays are added as properties but in the console are undefined rather than Array[0]

Am I way off base in wanting to do this, or wanting to do it this way?

Go easy! Ember newb! :D

1
"The arrays are added as properties but in the console are undefined rather than Array[0]". How are you checking this? - nem035
console.log(this); from within one of my controller actions. I can expand the Class in the console and see it says "filter_breadcrumb: undefined" When I instead add filter_breadcrumb: [], ... directly to the controller and do the same I see: filter_breadcrumb: Array[0] - tarponjargon
Have you considered to use a mixin? - Lux
I actually tried creating a mixin and importing it into the route and the controller. Couple issues. First, I don't want the properties like q, paging, search_sort, etc. to be set on the route (only the controller). And there's a namespace issue with queryParams. For example, the controller needs an array called queryParams, and in order to set refreshModel=true, the route wants an array of hashes called queryParams. So I can't put queryParams in the mixin, they have to be kept separately for route and controller. - tarponjargon

1 Answers

1
votes

There is setProperties method for all objects in ember.

Please take a look at this twiddle and setProperties