Using Ractive.js, how do you Unselect a selected select box?

时间:2016-04-04 17:35:41

标签: ractivejs

I am using Ractive.js v0.7.3, and I have a need to unselect a select box, but cannot find in the Ractive documentation how to do it.

In my select, the first option is empty (has no value and says "Select..."), so I tried setting the value to null like so:

rjs.set('selected.' + cfg.nodeType + '.id', null);

and even verified that it was updating the value by doing the following before and after:

var test = rjs.get('selected.' + cfg.nodeType + '.id');

which returned the correct id before and null after, but the prior value still displayed as selected in the UI.

I ended up using the following in jQuery:

function resetMenu(cfg) {
    $('#' + cfg.nodeType + 'Select').attr('selectedIndex', -1)
        .find('option:selected').prop('selected', false);
}

but then when I switch to new page, Ractive 'reselects' the former selection. So, I added the following thinking that Ractive didn't know about the change, but Ractive still 'reselects' the former selected value.

function resetMenu(cfg) {
    $('#' + cfg.nodeType + 'Select').attr('selectedIndex', -1)
        .find('option:selected').prop('selected', false);

    if (rjs) {
        rjs.update('navList.' + cfg.nodeType);
    }
}

I am thinking that if I could use Ractive to unselect the option, that would be ideal, but I cannot find in the Ractive.js documentation how to unselect a select option.

1 个答案:

答案 0 :(得分:1)

<强>更新

Ractive中的错误已得到修复。在边缘版本(v0.8.0)中,您现在可以ractive.set()任何值,如果没有匹配选项,则不会选择任何值。

原始回答:

如果没有与设定值匹配的选项,Ractive将选择第一个选项。每次更新选择时都会发生这种情况。我认为这是一个错误,并在GitHub上提出了问题。

目前,最好的选择是创建一个装饰器来处理取消选择:

{{selected}}<br>

<select value="{{selected}}" decorator="unselect: {{selected}}">
  <option>1</option>
  <option>2</option>
</select>
var ractive = new Ractive({
  el: 'body',
  template: '#template',
  data: { selected: null },
  decorators: {
    unselect: function (select, value) {
      // use ractive.set('selected', null) in your code to unselect
      if (value === null) {
        select.selectedIndex = -1;
        this.updateModel();
      }

      return {
        teardown: function () {}
      }
    }
  }
});

演示:https://jsfiddle.net/xubo91oh/