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

旧城冷巷雨未停 提交于 2019-12-11 09:41:59

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/25756836/emberjs-how-to-set-another-property-from-computed-property-when-the-latter-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!