RactiveJS dynamic variable name

时间秒杀一切 提交于 2020-01-07 06:51:05

问题


I'm curious if I can somehow use dynamic variable names in templates. For example, I'm having a loop, though a type of units in my game:

{{# config.units:unit }}
    <input type="text" id="unit_{{unit}}" class="toTrain selectable" value="" placeholder="0" />
{{/ config }}

Where the value of the input should return the value of {{units_1}} for example, which represents the amount of units (type 1).

I could easily do some external object and store the amount of units for each of them but, I was wondering if I can keep the data binded because somewhere in the template there will be a total needed resources which is calculated whith these values.

The only "solution" which came into my head was to get rid of the loop and manually write the units in the template. But, when units change, I also need to change the template, and.. the real template structure for one unit is a bit bigger than this snippet.

Example:

<input value="{{units_1}}" />
<input value="{{units_2}}" />

And I was looking for something like:

<input value="{{'units_'+unit}}" />

Which is obviously not working and not even supposed to work this way. But, thats why I'm here right ? To raise questions.

Regards !


回答1:


Try to use write getUnit function:

{{# config.units:unit }}
    <input type="text" id="{{ getUnit(unit) }}" class="toTrain selectable" value="" placeholder="0" />
{{/ config }}

Component:

Ractive.extend({
  init:function(){
        self.set("getUnit", function (id) {
            return self.get("config.units.unit_"+id);
        });
  }
})


来源:https://stackoverflow.com/questions/25460380/ractivejs-dynamic-variable-name

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