Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selectize.js: onItemAdd event triggered when silently adding an item

Using Selectize.js, I'm trying to initialize the dynamically pre-select one of the item of the list without triggering the onItemAdd event. In the following code, the event is triggered even if the silent parameter is truthy:

$(function () {
    $('select').selectize({
        onItemAdd: function () {
            alert("Add item");
        }
    });
    // this triggers an the event
    $('select')[0].selectize.addItem('2', true);
});

JSFiddle: http://jsfiddle.net/zuzat0dc/1/

According to the documentation:

  • addItem(value, silent): "Selects" an item. Adds it to the list at the current caret position. If "silent" is truthy, no change event will be fired on the original input.

Any idea how to avoid triggering the onItemAdd event? Is the silent parameter b0rked or should I use the change event instead?

like image 913
Romain G Avatar asked Mar 12 '15 14:03

Romain G


1 Answers

A quick fix that worked for me was to keep a state flag and refer to it in the event handler...

$(function () {

  var initialising = true;

  $('select').selectize({
    onItemAdd: function () {
      if(!initialising) { 
        alert("Add item");
      }
    }
  });

  // this triggers an the event
  $('select')[0].selectize.addItem('2', true);

  initialising = false;
});
like image 137
SwishWez Avatar answered Sep 18 '22 00:09

SwishWez