简体   繁体   中英

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

I am trying to integrate Select2 within a Marionette ItemView.

The problem: I want to initialize the Select2 with already-selected values, but the selected elements are still available in the dropdown. If I clear the box then manually reselect the items from the dropdown, the items are then properly removed from the dropdown.

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:

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

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.

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.

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') .

You can do it even shorter like this.$('selector') .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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