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: /
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?
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/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?
-
1
Note: I could use the
off(...)
andon(...)
functions to disable the handler, add the item then re-enable to handler, but that doesn't look like the way it should be done =/ – Romain G Commented Mar 12, 2015 at 14:03 - What do you run .off() and .on()? The original select? – temuri Commented Dec 17, 2017 at 15:11
-
I'm pretty sure it was the
.on()
and.off()
event methods of the selectize instance – Romain G Commented Dec 18, 2017 at 15:54
3 Answers
Reset to default 7A 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;
});
The silent parameter in addItem(value, silent)
affects only to the fact whether or not the change
event. You can't avoid item_add
event with silent = true
.
The only thing that worked for me was to store item_add
event locally, remove it from selectize instance and set it back after I added the item:
onItemAdd: function(val) {
var e = this._events['item_add'];
delete this._events['item_add'];
this.addItem(123);
this._events['item_add'] = e;
}