parsley/app/assets/javascripts/ingredients.js

88 lines
2.2 KiB
JavaScript
Raw Normal View History

2016-07-05 13:07:20 -05:00
window.INGREDIENT_API = {};
2016-01-24 19:06:26 -06:00
(function($) {
2016-01-28 14:19:51 -06:00
function initializeEditor($ingredientForm) {
usdaFoodSearchEngine.initialize(false);
var $typeahead = $ingredientForm.find(".ndbn_typeahead");
$typeahead.typeahead_search({
searchUrl: '/ingredients/usda_food_search.html',
2016-07-05 13:07:20 -05:00
resultsContainer: $ingredientForm.find(".ndbn_results")
2016-01-28 14:19:51 -06:00
},{
name: 'usdaFoods',
source: usdaFoodSearchEngine,
2016-09-28 17:08:43 -05:00
limit: 20,
2016-01-28 14:19:51 -06:00
display: function(datum) {
return datum.name;
}
});
$typeahead.on("typeahead_search:selected", function(evt, item) {
2016-07-05 13:07:20 -05:00
selectNdbn($ingredientForm, item.ndbn);
2016-01-28 14:19:51 -06:00
});
2016-07-05 13:07:20 -05:00
$ingredientForm.on("click", ".ndbn_results .food_result", function(evt) {
2016-01-28 14:19:51 -06:00
var $item = $(evt.target);
var ndbn = $item.data("ndbn");
2016-07-05 13:07:20 -05:00
selectNdbn($ingredientForm, ndbn);
2016-07-29 11:06:10 -05:00
return false;
2016-01-28 14:19:51 -06:00
});
}
2016-07-05 13:07:20 -05:00
function selectNdbn($ingredientForm, ndbn) {
2016-01-28 14:19:51 -06:00
var id = $ingredientForm.find("input.id").val();
$ingredientForm.find("input.ndbn").val(ndbn);
$ingredientForm.attr("action", "/ingredients/" + id + "/select_ndbn").attr("data-remote", "true");
2016-07-05 13:07:20 -05:00
$ingredientForm.submit();
}
function customTokenizer(str) {
if (str) {
var cleaned = str.replace(/,/g, "");
return Bloodhound.tokenizers.whitespace(cleaned);
} else {
return [];
}
2016-01-28 14:19:51 -06:00
}
2016-07-05 13:07:20 -05:00
window.INGREDIENT_API.initialize = function() {
var $ingredientForm = $("#ingredient_form");
if ($ingredientForm.length) {
initializeEditor($ingredientForm);
}
};
2016-01-24 19:06:26 -06:00
var usdaFoodSearchEngine = new Bloodhound({
initialize: false,
datumTokenizer: function(datum) {
2016-01-28 14:19:51 -06:00
var str = datum ? datum.name : null;
2016-07-05 13:07:20 -05:00
return customTokenizer(str);
2016-01-24 19:06:26 -06:00
},
2016-07-05 13:07:20 -05:00
queryTokenizer: customTokenizer,
2016-01-24 19:06:26 -06:00
identify: function(datum) { return datum.ndbn; },
sorter: function(a, b) {
if (a.name < b.name) {
return -1;
} else if (b.name < a.name) {
return 1;
} else {
return 0;
}
},
remote: {
url: '/ingredients/usda_food_search.json?query=%QUERY',
wildcard: '%QUERY'
}
});
2016-07-27 22:30:57 -05:00
$(document).on("turbolinks:load", function() {
2016-07-05 13:07:20 -05:00
window.INGREDIENT_API.initialize();
2016-01-24 19:06:26 -06:00
});
})(jQuery);