discourse/app/assets/javascripts/discourse/views/combo-box.js.es6

94 lines
2.6 KiB
Text
Raw Normal View History

/**
This view handles rendering of a combobox
@class ComboboxView
@extends Discourse.View
@namespace Discourse
@module Discourse
**/
export default Discourse.View.extend({
tagName: 'select',
attributeBindings: ['tabindex'],
classNames: ['combobox'],
valueAttribute: 'id',
buildData: function(o) {
var data = "";
if (this.dataAttributes) {
this.dataAttributes.forEach(function(a) {
data += "data-" + a + "=\"" + o.get(a) + "\" ";
});
}
return data;
},
render: function(buffer) {
var nameProperty = this.get('nameProperty') || 'name',
none = this.get('none');
2013-07-12 16:24:15 -04:00
// Add none option if required
if (typeof none === "string") {
buffer.push('<option value="">' + I18n.t(none) + "</option>");
} else if (typeof none === "object") {
buffer.push("<option value=\"\" " + this.buildData(none) + ">" + Em.get(none, nameProperty) + "</option>");
}
var selected = this.get('value');
if (!Em.isNone(selected)) { selected = selected.toString(); }
if (this.get('content')) {
var self = this;
this.get('content').forEach(function(o) {
var val = o[self.get('valueAttribute')];
if (!Em.isNone(val)) { val = val.toString(); }
var selectedText = (val === selected) ? "selected" : "";
2014-03-19 06:04:43 -04:00
buffer.push("<option " + selectedText + " value=\"" + val + "\" " + self.buildData(o) + ">" + Handlebars.Utils.escapeExpression(Em.get(o, nameProperty)) + "</option>");
});
}
},
valueChanged: function() {
var $combo = this.$(),
val = this.get('value');
if (val !== undefined && val !== null) {
$combo.val(val.toString());
} else {
$combo.val(null);
}
$combo.trigger("liszt:updated");
}.observes('value'),
contentChanged: function() {
this.rerender();
}.observes('content.@each'),
_initializeCombo: function() {
var $elem = this.$(),
self = this;
// Workaround for https://github.com/emberjs/ember.js/issues/9813
// Can be removed when fixed. Without it, the wrong option is selected
this.$('option').each(function(i, o) {
o.selected = !!$(o).attr('selected');
});
2014-05-11 00:50:03 -04:00
$elem.select2({formatResult: this.template, minimumResultsForSearch: 5, width: 'resolve'});
var castInteger = this.get('castInteger');
2014-05-11 00:50:03 -04:00
$elem.on("change", function (e) {
var val = $(e.target).val();
if (val.length && castInteger) {
val = parseInt(val, 10);
}
self.set('value', val);
});
}.on('didInsertElement'),
willClearRender: function() {
var elementId = "s2id_" + this.$().attr('id');
Ember.$("#" + elementId).remove();
}
});