jQuery 및 MagicSuggest를 사용하여 단일 필드의 자동 제안 기능을 초기화하는 다음 코드를 설정했습니다. 비교적 간단합니다. MagicSuggest로 다른 필드를 초기화 할 때 사용하기 때문에 약간의 모듈화가 있습니다. 하나의 관계없는 부분은 정식 이름 변환이지만,이 특정 데이터 세트를 처리하는 데 필요한 함수입니다. 아래 내가 이전에 제출 한 데이터로 미리 채울이 하나 개의 필드에 무엇을해야하고, 모든 말했다약속을 포함하여이 Javascript 메서드 집합을 일반화하는 방법은 무엇입니까?
/**
* Initialize Flights From autosuggest feature
* @return {void}
*/
function initFlightsFromAutosuggest() {
// Flights From Typeahead *************************************
var msField = $('#magicsuggest.direct_flights_from');
var ms = msField.magicSuggest({
id : 'direct_flights_from',
name : 'direct_flights_from',
minChars : 1,
highlight : false,
valueField : 'id',
displayField : 'name',
placeholder : getMSPlaceholder(msField, 'City'),
resultAsString: true,
useTabKey : true,
useCommaKey : true,
useZebraStyle : true,
hideTrigger : true,
sortOrder : 'canonical_name',
maxDropHeight : 500,
data : '/api/v1/cities',
defaultValues : msField.attr('data-default').split(','),
renderer : function(data) { return convertCanonical(data.canonical_name) }
});
// Once loaded, add pre-selected values if there are any
$(ms).on('load', addDefaults(ms, msField));
}
/**
* Gets placeholder value for MagicSuggest instances
* @param {element} el DOM element
* @param {string} defaultString Default string to use
* @return {string}
*/
function getMSPlaceholder(el, defaultString) {
if (el.attr('data-default').length > 0) {
return '';
}
return defaultString;
}
/**
* Converts canonical name into city, state string (dropping country, fixing spacing)
* @param {string} canonical_name Full canonical name
* @return {string} Short name, without country
*/
function convertCanonical(canonical_name) {
if (typeof canonical_name !== 'undefined') {
canonical_name = canonical_name.replace(',United States', '');
canonical_name = canonical_name.replace(',', ', ');
return canonical_name;
}
// Not sure what to do if it's undefined
return;
}
(내가 함께하는 데 문제가 문제 ... 아래에 설명).
/**
* Adds pre-selected values (ids) loaded into the 'data-default' attribute into the input field
* @param {object} ms MagicSuggest instantiation
* @param {element} msField DOM element used by MagicSuggest
*/
function addDefaults(ms, msField) {
// Get the default attribute value as an array
var defaultIds = msField.attr('data-default').split(',');
// Setup array of requests
var requests = [];
// Push all the requests into an array
$.each(defaultIds, function(index, id) {
requests.push($.getJSON('/api/v1/cities/' + id));
});
// Create a promise, and when all the requests are done (promises fulfilled)
// Send the args (json) to the .done callback
var promise = $.when.apply($, requests).then(function() {
var args = Array.prototype.slice.call(arguments);
return args.map(function(arg) { return arg[0] });
});
// Setup the callback function for 'done'
promise.done(function(json) {
// Setup results array
var results = [];
// Got an auth error from the API, so return early. No results.
if (typeof(json[0].auth) === 'object') {
return false;
}
// For each item, add the proper structure to the results array
$.each(json, function (index, id) {
results.push({
value: json[index][0]['city']['id'],
name: json[index][0]['city']['name']
});
});
var resultPromise = $.when.apply($, results).then(function() {
var args = Array.prototype.slice.call(arguments);
return args.map(function(arg) { return arg });
});
resultPromise.done(function(results) {
ms.setValue(results);
ms.setDataUrlParams({});
$('.input')
});
});
}
이 일반화 할 수있는 방법이 있어야한다, 그러나 나는 내가 이해의 벽을 치는 봤는데 약속에 새로 온 사람과 $.Deferred
.
내가 (아마 사용하여 ID를 생각을)를 $.getJSON()
방법에 대해 서로 다른 URL을 사용하는 것입니다 MagicSuggest으로 인스턴스화됩니다 다른 필드
ms
이
resultPromise.done
에서 정의되지 않기 때문에
는 최대한 빨리 깨는 시작으로 떨어져 addDefaults()
나는 그들에 ID를하고 $.each
명령 내부 json
구조의 URL을 문제를했다.
어떻게하면 이것을 재사용 할 수 있습니까? 약속 및 지연에 대한 설명/설명은 항상 도움이됩니다.