rollingBalls
rollingBalls

Reputation: 1878

Emberjs - how to set another property from computed property when the latter is not on the template?

This is a follow-up from my previous question, thought it deserves a different post.

I what to set a data subset to a different property and have it available (and update-able) on the template. So I thought I 'd create an empty property and simply set its value.

The updated template:

    {{#each test12}}
        {{businessname}}
    {{/each}}

The controller:

test12: [],
test11: function(){
    var bms = this.get('businessmatches').filterBy('type', 'hardware');
    this.set('test12', bms);
    return bms;
}.property('businessmatches.@each.[type]'),

The problem is that this does not work. The interesting thing is that if I change the template to

    {{#each test12}}
        {{businessname}}
    {{/each}}
    <hr/>
    {{#each test11}}
        {{businessname}}
    {{/each}}

then it works!!! :o

I could hide the second part on a display:none; div or I could have the logic directly on test12 but the behavior was a complete surprise (I thought set didn't work at first). Am I missing something? Is there a proper way of doing it?

Upvotes: 1

Views: 587

Answers (1)

user663031
user663031

Reputation:

In general, side effects in computed properties (in your case, setting test12) are best avoided. They make the program hard to reason about.

In your case, the problem is that merely referring to test12 does not compute anything. Ember has no way to know that test12 is getting set inside test11 and that it might need to run that. When you then refer to test11 from the template, it is computed, with the side effect of setting test12, which updates the template (so fast you can't see it; to test this, you could add a {{debugger}} between the test12 and test11 parts of the template, and when you stop in the debugger, you will notice that the test12 part is still empty).

Depending on what you are trying to accomplish, you could do something like test12: function() { return this.get('test11'); }.property('test11'), or test12: Ember.computed.alias('test11'), which is the same thing.

Upvotes: 1

Related Questions