0

I'm facing an issue with selectize.js when using the onItemAdd parameter of the constructor (https://github.com/brianreavis/selectize.js/blob/master/docs/usage.md#callbacks).

Let's say I have a class which instance will hold and manage the selectize instance. I want to add options dynamically, and to have a method of my class called whenever an option is selected. In the code below, The <select id="#select"></select> is not mentioned but does exist.

function Class() {
    var self = this;
    // create the selectize instance
    $('#select1').selectize({
        onItemAdd: self._func
    });
    var select = $('#select1')[0].selectize;
    select.addOption({value: 'hello', text: 'Hello'});
    select.addOption({value: 'world', text: 'World'}); 

    self._func = function (value) {
        alert(value);   
    }
}

$(function() {
    new Class();
});

Surprisingly, the object method self._func is never called when the items are selected. However, if I replace it by something like onItemAdd: function (value) { self._func(value); }, the object method self._func is called as expected!

JsFiddle that demonstrate the issue: https://jsfiddle.net/qDL37/1/

Any reason that could explain this behaviour?

Romain G
  • 1,276
  • 1
  • 15
  • 27

1 Answers1

1

Alright, I just finished to write the post when I understood the reason. In the example above, when the selectize instance is created, self._func is still undefined.

To fix this, simply declare _func before creating the selectize instance.

Romain G
  • 1,276
  • 1
  • 15
  • 27