@each one level deep, but I need to go two level's deep


#1

I have to access a property that is two level’s deep on my controller, but the [] only can access one level deep via the emberjs guide.

model(params) {
	params.paramMapping = {
		page: "page",
		perPage: "per_page",
		total_pages: "pages"
	};

	return this.findPaged('contractf', params);
},

setupController(controller, model) {
	model.forEach(function(item) {
		item.set('sale_price', item.set('sale_price', item.get('dealers_sched_id.sale_price'));
	});

	controller.set('content', model);
},

Above, I have my model which is basically fetching all records in a pagination format in the contractf model. Then I set up my controller and loop through all those models and bind a sale_price property that goes into it’s relationship to get the sale_price in the correct model relation.

Now in my template, I have this:

new_suggested_price: Ember.computed('selectedItems', 'selectedItems.[].sale_price', function() {
	var ret = 0;

	this.get('selectedItems').filterBy('car_used', 'N').forEach(function(contract){
		var salePrice = contract.get('sale_price');

		if (salePrice) {
			ret += (salePrice*100);
		}
	});

	return ret/100; // We *100/100, so we avoid a floating point calc error.
}),

Basically just gives me a number that is easily format-able. As you can see it depends on the selectedItems (which is basically the model, but filters by a property). So I have to go into each model item and find that sale_price I property I set and if it changes, this computed property will update. Reading Ember’s guide, I couldn’t do selectedItems.[].dealers_sched_id.sale_price because it only goes one level deep.

I thought setting a property on setupController would fix that issue, but it doesn’t seem to because I’m still getting NaN as the sale_price value.

Now if I set a setTimeout function for 500 ms, it populates fine… How do I get it defined on page load?

Thank you for any help.


#2

You can create an intermediate step and do this in two steps (usually preferred way to go).

Or you can create a custom computed to create the intermediate step for you, similar to how I made one here for filterBy two levels deep. https://gist.github.com/runspired/3d9835deff2aa46e3a59


#3

@jthoburn I read through your example and I’m not understanding it at all. I don’t see Ember js components being used or anything. :x: I’m unsure on how my example would look given your example you posted.


#4

This is what fixed it for me and creating an alias to it in the model: http://stackoverflow.com/questions/35689841/ember-js-2-3-implement-each-property-observer-on-a-hasmany-relationship