简体   繁体   English

emberjs在模板渲染后即时添加代码

[英]emberjs add code on the fly, after template render

In emberjs, you can add code to your template file: 在emberjs中,您可以将代码添加到模板文件中:

{{input type="text" value=color}}

the template then renders. 模板然后呈现。 But the question is, how can you add this dynamically after the template renders? 但是问题是,如何在模板渲染后动态添加呢? For example, I want to add a button, to generate new input fields (colors), and the user can continue to add new colors as needed? 例如,我想添加一个按钮,以生成新的输入字段(颜色),并且用户可以根据需要继续添加新的颜色吗? How would one go about doing this? 人们将如何去做呢?

First of all, if you want to let user add another input for color, I am sure that you want to somehow access the value user inputs after all - eg in some action. 首先,如果您想让用户为颜色添加另一个输入,我肯定您想毕竟以某种方式访问​​用户输入的值-例如,在某些操作中。 Therefore, you will have to make some bindings that will store that values. 因此,您将必须进行一些绑定来存储该值。

Let's say you need to store them in some kind of an array - eg colors . 假设您需要将它们存储在某种数组中,例如colors This array will be initially containing only one object, automatically added when user enters the route. 此数组最初将仅包含一个对象,当用户输入路线时会自动添加。 This setup (eg in setupController hook in route) may look like this: 此设置(例如,路由中的setupController挂钩)可能如下所示:

setupController: function(controller, model) {
  controller.set("colors", []);
  controller.get("colors").pushObject({ value: "" });
}

And let's handle the click on the button by an action in controller: 让我们通过控制器中的一个动作来处理按钮的单击:

actions: {
  handleClick: function() {
    this.get("colors").pushObject({ value: "" });
  }
}

Then, your template can look like this: 然后,您的模板如下所示:

{{#each color in colors}}
  {{input type="text" value=color.value}}
{{/each}}

Using pushObject method make pushing binding-compliant. 使用pushObject方法使推送符合绑定。 Every time you push anything to colors array, the template will automatically rerender and inject another input field with properly binded value to color.value . 每次将任何内容推送到colors数组时,模板都会自动重新渲染并注入另一个将value正确绑定到color.value input字段。 Thanks to that, in some other action (like submit) you can access all the values provided by the user and process them as you want. 因此,在其他操作(例如提交)中,您可以访问用户提供的所有值并根据需要对其进行处理。

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

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