javascriptjqueryjquery-eventstwitter-typeahead

Tagsmanager.js 3.0 with tritter-typeahead updating the wrong fields


I'm trying to make a general function to enable typeahead tag lookup. I was having some success with this until I tried to generalize the function. Now it seems to work but updates the wrong fields.

I think the line that creates var tmApi is not keeping it local. Or at least the callback is accessing the wrong variable. And idea how to get the callback to reference the local one?

<div class="tag-container" id="skills-container"></div>
<input class="form-control" id="skills-add" type="text" 
data-tag="skills" data-prefill="${traveler.skills}" data-tagfile="/inc/ajax/skills.json">
<input type="hidden" id="skills" name="skills">

<script>setupTags();</script>

and

function setupTags(){

    var fields = $('INPUT[type="text"]');
    for (var i=0; i<fields.length; i++){
            
        if (fields[i].getAttribute("data-tag")){
            var tag     = fields[i].getAttribute("data-tag");
            var prefill = fields[i].getAttribute("data-prefill");
            var tagfile = fields[i].getAttribute("data-tagfile");
            
            console.log(tag);
            
            var tmApi = $('#'+tag+'-add').tagsManager({
                backspace: [],
                tagsContainer: '#'+tag+'-container',
                delimiters: [9, 13, 44], // tab, enter, comma
                prefilled: prefill,
                output: '#'+tag
            });
            
            console.log(tmApi);
            
            var tagsdb = new Bloodhound({
                  datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.name); },
                  queryTokenizer: Bloodhound.tokenizers.whitespace,
                  prefetch: {
                    url: tagfile,
                    cacheKey: tag,
                    ttl: 600000, //10 min
                    filter: function(list) {
                        return $.map(list, function(tag) { return { name: tag }; });
                    }
                  }
            });
            tagsdb.initialize();
            
            $('#'+tag+'-add').typeahead(null, {
                name: tag,
                displayKey: 'name',
                source: tagsdb.ttAdapter()
            }).on('typeahead:selected', function (e, d, s) {
                tmApi.tagsManager("pushTag", d.name);
            });
            
        }
    }
}

Solution

  • Solved it by wrapping in a Closure