简体   繁体   English

带Backbone.Marionette的Select2:未隐藏预选值

[英]Select2 with Backbone.Marionette: Pre-selected values not hidden

I am trying to integrate Select2 within a Marionette ItemView. 我正在尝试在Marionette ItemView中集成Select2。

The problem: I want to initialize the Select2 with already-selected values, but the selected elements are still available in the dropdown. 问题:我想用已经选择的值初始化Select2,但是选择的元素在下拉列表中仍然可用。 If I clear the box then manually reselect the items from the dropdown, the items are then properly removed from the dropdown. 如果清除此框,然后从下拉列表中手动重新选择项目,则这些项目会从下拉列表中正确删除。

Javascript: Javascript:

View.Profile = Marionette.ItemView.extend({
    template: profileTpl,
    onShow: function(){
      var $select = this.$("#categories"); // grabs the element for Select2
      $select.select2();                   // build the Select2 element
      $select.select2("val", ["american", "french", "italian"]); // select values
    }

HTML: HTML:

<select id="categories" data-placeholder="Add a category..." multiple class="form-control" tabindex="8">
  <option></option>
  <option value="american">American</option>
  <option value="french">French</option>
  <option value="italian">Italian</option>
  <option value="indian">Indian</option>
</select>

I can do this on a single html example page with no trouble. 我可以在单个html示例页面上完成此操作,而不会遇到麻烦。

Using Marionette's onShow, the "tag" elements correctly displayed in the Select2 box, but when I click the box to select different options, all options are still available. 使用Marionette的onShow,“标记”元素会正确显示在Select2框中,但是当我单击该框以选择其他选项时,所有选项仍然可用。

I suspect there is some event not properly attached to the Select2 element because of the way I'm attaching the Select2 element in the onShow event. 我怀疑由于我在onShow事件中附加Select2元素的方式,某些事件未正确附加到Select2元素。

Here is working example of your issue. 是您的问题的有效示例。

Just one note related to your code. 仅一则注释与您的代码有关。 It's a good practice, when accessing an element of view, use this.$el.find('selector') reference instead of querying it via jquery $('selector') . 这是一个好习惯,当访问视图元素时,请使用this.$el.find('selector')引用,而不要通过jquery $('selector')进行查询。

You can do it even shorter like this.$('selector') . 您可以像this.$('selector')更短地完成它this.$('selector')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM