(function() {
Luca.fields.SelectField = Luca.core.Field.extend({
form_field: true,
events: {
"change select": "change_handler"
},
hooks: ["after:select"],
className: 'luca-ui-select-field luca-ui-field',
template: "fields/select_field",
includeBlank: true,
blankValue: '',
blankText: 'Select One',
initialize: function(options) {
this.options = options != null ? options : {};
_.extend(this, this.options);
_.extend(this, Luca.modules.Deferrable);
_.bindAll(this, "change_handler", "populateOptions", "beforeFetch");
Luca.core.Field.prototype.initialize.apply(this, arguments);
this.input_id || (this.input_id = _.uniqueId('field'));
this.input_name || (this.input_name = this.name);
this.label || (this.label = this.name);
if (_.isUndefined(this.retainValue)) return this.retainValue = true;
},
afterInitialize: function() {
var _ref;
if ((_ref = this.collection) != null ? _ref.data : void 0) {
this.valueField || (this.valueField = "id");
this.displayField || (this.displayField = "name");
this.parseData();
}
try {
this.configure_collection();
} catch (e) {
console.log("Error Configuring Collection", this, e.message);
}
this.collection.bind("before:fetch", this.beforeFetch);
return this.collection.bind("reset", this.populateOptions);
},
parseData: function() {
var _this = this;
return this.collection.data = _(this.collection.data).map(function(record) {
var hash;
if (!_.isArray(record)) return record;
hash = {};
hash[_this.valueField] = record[0];
hash[_this.displayField] = record[1];
return hash;
});
},
afterRender: function() {
var _ref, _ref2;
this.input = $('select', this.el);
if (((_ref = this.collection) != null ? (_ref2 = _ref.models) != null ? _ref2.length : void 0 : void 0) > 0) {
return this.populateOptions();
} else {
return this.collection.trigger("reset");
}
},
setValue: function(value) {
this.currentValue = value;
return Luca.core.Field.prototype.setValue.apply(this, arguments);
},
beforeFetch: function() {
return this.resetOptions();
},
change_handler: function(e) {
return this.trigger("on:change", this, e);
},
resetOptions: function() {
this.input.html('');
if (this.includeBlank) {
return this.input.append("");
}
},
populateOptions: function() {
var _ref,
_this = this;
this.resetOptions();
if (((_ref = this.collection) != null ? _ref.each : void 0) != null) {
this.collection.each(function(model) {
var display, option, selected, value;
value = model.get(_this.valueField);
display = model.get(_this.displayField);
if (_this.selected && value === _this.selected) selected = "selected";
option = "";
return _this.input.append(option);
});
}
this.trigger("after:populate:options", this);
return this.setValue(this.currentValue);
}
});
Luca.register("select_field", "Luca.fields.SelectField");
}).call(this);