0

I have the following code setup to initialize a single field's autosuggest feature using jQuery and MagicSuggest. It's relatively straight forward. I have modularized a bit of it because I intend on using it to initialize other fields as well with MagicSuggest. One extraneous part is the canonical name conversion, but it's a necessary function for this particular data set I'm working with. (Problem I'm having trouble with explained below ...)

/**
 * 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;
}

That all said, below is what I have to do to pre-populate this one field with data previously submitted.

/**
 * 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')
        });
    });
}

There has to be a way to generalize this, but I'm new at promises and $.Deferred so I've been hitting a wall of understanding.

The other fields I'll be instantiating with MagicSuggest will be using different URLs for the $.getJSON() method (probably all using IDs though) (used for finding what the user had previously chosen, thus what to pre-populate the field with), and will obviously have different JSON responses for those calls. So, the trouble spots for me are how to get this all to work together and still DRY.

As soon as I start breaking apart addDefaults() I hit problems because ms is undefined in resultPromise.done, the URLs with the IDs in them, and the json structure inside the $.each command.

How would you refactor this to be more re-usable? Comments/explanations on promises and deferred are always helpful too.

1 Answer 1

0

With a fresh head after a few days rest, and with the insight of this post I realized I didn't need to do all this just to add default values. Thankfully, just adding the following to the init worked perfectly: value: msField.attr('data-default').split(','), (I'm adding the values into the HTML under the data-default attribute via PHP.

Code: deleted.

Problem: solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.