var Select;
module.exports = Select = {
create: function() {
var instance = Object.assign({}, this.prototype);
this.init.apply(instance, arguments);
return instance;
},
init: function(params) {
this.events = jQuery({});
this.options = params.options || [];
this.value = '';
if (params.elem) {
// select tag in DOM
this.$select = jQuery(params.elem);
// read values from DOM
this.$select.children().each(function(index, elem) {
this.options.push({
value: elem.value,
label: elem.innerText
});
}.bind(this));
}
else {
// select created programmatically
this.$select = jQuery('');
this.options.forEach(function(option) {
this.$select.append('');
}.bind(this));
}
this.$select.hide();
this.placeholder = params.placeholder || this.options.shift().label;
// wrapper
this.$select.wrap('
');
this.$wrapper = this.$select.closest('.c-select');
// input
this.$input = jQuery('');
this.$input.attr('placeholder', this.placeholder);
this.$wrapper.append(this.$input);
var icon = [
''
].join('\n');
this.$wrapper.append(icon);
this.$input.on('focus', function() {
this.showDropdown();
}.bind(this));
this.$input.on('blur', function() {
this.hideDropdown();
}.bind(this));
// dropdown
this.$dropdown = jQuery('');
this.options.forEach(function(option) {
this.$dropdown.append('' + option.label + '');
}.bind(this));
this.$wrapper.append(this.$dropdown);
this.$dropdown.on('mousedown', function(e) {
e.preventDefault();
});
this.$dropdown.on('click', 'li', function(e) {
var value = e.currentTarget.dataset.value;
var label = e.currentTarget.innerText;
this.update({
label: label,
value: value
});
this.$input.trigger('blur');
}.bind(this));
},
prototype: {
appendTo: function(elem) {
this.$wrapper.appendTo(elem);
},
on: function(eventName, callback) {
this.events.on(eventName, callback);
},
update: function(updated) {
this.value = updated.value;
this.$input.val(updated.label);
this.$select.val(this.value);
if (this.value) {
this.events.trigger('change', this.value);
}
},
reset: function() {
this.update({
label: '',
value: ''
});
this.events.trigger('reset');
},
showDropdown: function() {
this.isOpen = true;
this.$dropdown.addClass('is-visible');
},
hideDropdown: function() {
this.isOpen = false;
this.$dropdown.removeClass('is-visible');
},
destroy: function() {
this.$wrapper.remove();
this.$wrapper = null;
}
}
};