How to update variables that are inside a helper body in an Ember template

137 Views Asked by At

Imagine a property myNumber in a controller that has a different random number every second. With this template you will see this change every second:

<h4>Random number</h4>
<p>{{myNumber}}</p>

However, when the number is only referenced inside a helper (e.g. #if or #each), the number is not updated anymore. This will only show the initial value:

<h4>Random number</h4>
{{#if model}}
    <p>{{myNumber}}</p>
{{/if}}

(Note that myNumber has no relation to model. Just using some random truthy property.)

Interestingly, when you add the reference to the property back to the root of the document, the previously static numbers will now also update:

<h4>Random number</h4>
{{myNumber}} -- Without this reference, references below won't update.
{{#if model}}
    <p>{{myNumber}}</p>
{{/if}}

How can I have myNumber inside the helpers update, without showing the number in the root of my template?

I've tried adding the reference in html comments, but that doesn't work. I assume Ember doesn't draw elements that are not in the DOM:

<h4>Random number</h4>
<!-- {{myNumber}} -->
{{#if model}}
    <p>{{myNumber}}</p>
{{/if}}

What does work is adding the value to the DOM, but hiding it. However, this is an ugly solution:

<h4>Random number</h4>
<span style="display:none">
    {{myNumber}}
</span>
{{#if model}}
    <p>{{myNumber}}</p>
{{/if}}
1

There are 1 best solutions below

1
On

Using an arrow function will solve your problem.

alt