"use strict";
//
//A dropdown menu. Pass it a container and an array of data, and it will build the button, caret, and list of selectable elements inside the container.
//
(function($) {
var Dropdown = function($element, data, options) {
var _this = this;
var textSpan = $("" + options.defaultText + "");
this.$element = $element;
this.options = $.extend({}, Dropdown.DEFAULTS, options);
this.$selected = null;
this.$textSpan = null;
this.selectionHandler = function(event) {
_this.$selected = $(this);
_this.$selected.addClass(_this.options.selectionClass).siblings().removeClass(_this.options.selectionClass);
textSpan.text(_this.$selected.text());
};
var button = $("");
var caretSpan = $("");
button.appendTo($element);
textSpan.appendTo(button);
caretSpan.appendTo(button);
//Save this for later use when setting the selection manually.
this.$textSpan = textSpan;
var ul = $("
");
ul.appendTo($element);
for(var dataIndex = 0; dataIndex < data.length; dataIndex++) {
var nextData = data[dataIndex];
var text = $.isFunction(options.textAttr) ? options.textAttr(nextData) : nextData[options.textAttr];
var li = $("
")
li.appendTo(ul);
li.data('object', nextData);
li.bind("click", this.selectionHandler);
}
};
Dropdown.DEFAULTS = {
textAttr: 'name', //The attribute of the data elements to use for the name. This can also be a function that takes the data object and returns the text.
defaultText: '', //The initial text if no selection is made. This will be taken from the
selectionClass: '', //The class to use for the selected element in the dropdown list.
buttonStyling: '',
buttonClasses: 'btn btn-default dropdown-toggle',
caretClasses: 'caret',
listItemClasses: ''
};
Dropdown.prototype.getSelection = Dropdown.prototype.getSelected = function() {
return this.$selected.data('object');
};
Dropdown.prototype.setSelection = Dropdown.prototype.setSelected = function(object) {
var listElements = this.$element.find("li");
for(var index = 0; index < listElements.length; index++) {
if($(listElements[index]).data('object').id == object.id) {
this.$selected = $(listElements[index]);
this.$selected.addClass(this.options.selectionClass).siblings().removeClass(this.options.selectionClass);
this.$textSpan.text(this.$selected.text());
break;
}
}
};
$.fn.buildDropdown = function(data, options) {
for(var index = 0; index < this.length; index++) {
var $next = $(this[index]);
var nextDropdown = new Dropdown($next, data, options);
$next.data("de.dropdown", nextDropdown);
}
}
$.fn.getDropdown = function() {
if(this.length > 0) {
return $(this[0]).data('de.dropdown');
}
}
})(jQuery);