Search code examples
jqueryruby-on-rails-4coffeescripttwitter-typeahead

Accessing data attributes of element with Twitter Typeahead.js


I use Rails to generate my forms. I want to use Twitter Typeahead to autocomplete the fields with model associations.

The following CoffeeScript code:

console.log $('.typeahead').data('source')

works and returns:

["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

Can I access the same data from within the typeahead function? The following code:

$('.typeahead').typeahead(
    name: 'test'
    local: $(this).data('source')
    console.log $(this).data('source'))

does not work and returns undefined.


Solution

  • The easiest way is to save a reference to the jQuery object and use that instead of this:

    $input = $ '.typeahead'
    $input.typeahead
        name: 'test'
        local: $input.data 'source'
    

    The problem is that $(this).data('source') is evaluated before it is passed to.typeahead(). At this point in time, this is still set to the global scope, which has no data attached to it.

    Another option, which works even if you have multiple .typeahead elements, is to manually invoke .each() rather than relying on .typeahead() to iterate over the selected elements itself:

    $('.typeahead').each ->
        $(this).typeahead
            name: 'test'
            local: $(this).data 'source'
    

    This works because functions passed to .each() are "fired in the context of the current DOM element, so the keyword this refers to the element" (see the docs).