首页 > 解决方案 > Dust.js 双向数据绑定

问题描述

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

<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。我将不得不添加另一个<p>与那辆特定汽车的描述。

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

标签: javascriptdata-bindingdust.js

解决方案


您仍然可以使用灰尘模板实现相同的效果

<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>

这是完整的示例要点


推荐阅读