简体   繁体   English

如何更新Ember模板中的辅助体内的变量

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

Imagine a property myNumber in a controller that has a different random number every second. 想象一下,控制器中的属性myNumber每秒具有不同的随机数。 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 (eg #if or #each ), the number is not updated anymore. 但是,当仅在助手内部引用该数字时(例如#if#each ), 该数字将不再更新。 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.) (请注意, myNumbermodel无关。仅使用一些随机的Truth属性。)

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? 如何在助手内部更新myNumber而不在模板的根目录中显示数字?

I've tried adding the reference in html comments, but that doesn't work. 我尝试在html注释中添加引用,但这不起作用。 I assume Ember doesn't draw elements that are not in the DOM: 我假设Ember不会绘制不在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. 起作用的是将值添加到DOM,但将其隐藏。 However, this is an ugly solution: 但是,这是一个丑陋的解决方案:

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

Using an arrow function will solve your problem. 使用箭头功能将解决您的问题。

ALT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM