【问题标题】:Ractive value not being set when select list is first loaded首次加载选择列表时未设置 Ractive 值
【发布时间】:2016-04-23 23:10:37
【问题描述】:

我正在使用 Ractive 并且有两个选择列表。第一个选择列表让用户选择他们的国家。如果他们选择“美国”,Ractive 将检查它并显示一个状态列表供用户选择他们的状态。例如:

<select value="{{country}}">
    <option value="CA">Canada</option>
    <option value="US">USA</option>
</select>

{{#if country == 'US'}}
    <select value="{{chosen_state}}">
        {{#states}}
            <option value="{{this.state_name}}">{{this.state_name}}</option>
        {{/}}
    </select>
{{/if}}

当此表单首次加载时,默认选择“加拿大”。一旦用户选择“美国”,状态列表就会显示得很好。但是,如果我尝试检查“chosen_state”的值,它将被设置为空而不是状态列表中的第一个状态。在我手动更改状态后,“chosen_state”值才会显示为状态值。

我是否必须等待手动事件触发更改事件,或者有什么方法可以使状态列表一呈现,它就会根据第一个状态自动更新它的值显示?在呈现时不必为每个选择列表触发更改事件会很好。

【问题讨论】:

    标签: ractivejs


    【解决方案1】:

    事实证明,这需要使用 updateModel 进行脏检查。我这样做了,如果选择字段发生更改,它会触发一个事件,该事件会在实例上调用 updateModel 以对 selected_state 字段进行脏检查。

    更新了选定的代码:

    <select value="{{country}}" on-change="countrychange">
        <option value="CA">Canada</option>
        <option value="US">USA</option>
    </select>
    
    {{#if country == 'US'}}
        <select value="{{chosen_state}}">
            {{#states}}
                <option value="{{this.state_name}}">{{this.state_name}}</option>
            {{/}}
        </select>
    {{/if}}
    

    在 ractive 中:

    ractive.on('countrychange', function(event) {
    
        this.updateModel();
    
    });
    

    替代解决方案可能包括观察模型以更新国家/地区,然后运行 ​​this.updateModel() 以及仅在所需的 keypath 上运行 updateModel,这样更有效。

    有关这方面的更多文档可在以下位置找到: http://docs.ractivejs.org/latest/ractive-updatemodel

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 2020-11-18
      • 2018-10-24
      • 2016-12-18
      相关资源
      最近更新 更多