73 lines
1.6 KiB
JavaScript
73 lines
1.6 KiB
JavaScript
(function($) {
|
|
|
|
function State() {
|
|
this.input = null;
|
|
this.outputUnit = null;
|
|
this.changed = false;
|
|
}
|
|
|
|
State.prototype.setInput = function(value) {
|
|
if (value != this.input) {
|
|
this.changed = true;
|
|
this.input = value;
|
|
}
|
|
};
|
|
|
|
State.prototype.setOutputUnit = function(value) {
|
|
if (value != this.outputUnit) {
|
|
this.changed = true;
|
|
this.outputUnit = value;
|
|
}
|
|
};
|
|
|
|
State.prototype.is_changed = function() {
|
|
return this.changed;
|
|
};
|
|
|
|
State.prototype.reset = function() {
|
|
this.changed = false;
|
|
};
|
|
|
|
$(document).on("ready page:load", function() {
|
|
|
|
var state = new State();
|
|
var $input = $("#input");
|
|
var $output = $("#output");
|
|
var $outputUnit = $("#output_unit");
|
|
|
|
var performUpdate = _.debounce(function() {
|
|
$.getJSON(
|
|
"/calculator/calculate",
|
|
{input: $input.val(), output_unit: $outputUnit.val()},
|
|
function(data) {
|
|
if (data.errors.input) {
|
|
$input.closest(".form-group").addClass("has-error");
|
|
} else {
|
|
$input.closest(".form-group").removeClass("has-error");
|
|
}
|
|
|
|
if (data.errors.output_unit) {
|
|
$outputUnit.closest(".form-group").addClass("has-error");
|
|
} else {
|
|
$outputUnit.closest(".form-group").removeClass("has-error");
|
|
}
|
|
|
|
$output.val(data.output);
|
|
}
|
|
);
|
|
|
|
}, 500);
|
|
|
|
$input.add($outputUnit).on('change blur keyup', function(evt) {
|
|
state.setInput($input.val());
|
|
state.setOutputUnit($outputUnit.val());
|
|
|
|
if (state.is_changed()) {
|
|
performUpdate();
|
|
state.reset();
|
|
}
|
|
});
|
|
|
|
});
|
|
|
|
})(jQuery); |