【问题标题】:Dust.js Two way data bindingDust.js 双向数据绑定
【发布时间】:2018-07-19 08:01:19
【问题描述】:

我有一个非常简单的下拉菜单。

<div>
    <select id="optionDropDown">
        <option value="volvo">{@pre type="content" key="dropdown.option1"/}</option>
        <option value="saab">{@pre type="content" key="dropdown.option2"/}</option>
        <option value="mercedes">{@pre type="content" key="dropdown.option3"/}</option>
        <option value="audi">{@pre type="content" key="dropdown.option4"/}</option>
    </select>
</div>

每当用户更改下拉菜单中的选择时,我都需要修改 UI。我将不得不添加另一个 &lt;p&gt; 以及该特定汽车的描述。

目前我正在使用 jQuery 执行此操作,但很想知道 Dust.js 中是否有一些内置方法可以通过修改 context 或任何其他方式来执行此操作。

【问题讨论】:

    标签: javascript data-binding dust.js


    【解决方案1】:

    您仍然可以使用dust templates 实现相同的效果

    <script type="text/dust" id="tpl">
      <p>Chose: {type}!</p>
    </script>
    <script type="text/javascript">
    
      var tpl_src = $('#tpl').html();
    
      // Compile the template under the name 'tpl'
      var tpl_compiled = dust.compile(tpl_src, 'tpl');
    
      // Register the template with Dust
      dust.loadSource(tpl_compiled);
    
      // Whenever a choice is made...
      $('select[id=types]').on('change', function() {
    
        // Using jQuery ----------------------
        // $('div#selections').append('<p>'+$(this).val()+'</p>');
    
        // Using dustjs ----------------------
    
        // Render the template
        dust.render('tpl', { type: $(this).val() }, function(err, out) {
    
          if(err) {
            console.log(err);
            return;
          }
    
          // `out` contains the rendered output.
          $('div#selections').append(out);
        });
    
      });
    
    </script>
    

    这是完整示例gist

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-24
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 2014-01-30
      • 2012-08-07
      • 1970-01-01
      相关资源
      最近更新 更多