3

I want to build a tags input like the one in StackOverflow. I am trying to use Meteor collections as the remote or prefetch data for Typeahead Bloodhound because I want to eventually use Bootstrap Tokenfield.

According to their documentation and examples, a url to the JSON data is absolutely required. How can I provide the data, preferably reactively, to Bloodhound? I have looked into the Meteor Typeahead package, but I can't figure out how to use it with the Meteor Tokenfield package.

Below is what I've tried to do, but it doesn't work. :(

<div class="control-group">
    <label class="control-label" for="users">Users</label>
    <div class="controls">
      <input type="text" class="form-control" id="tokenfield-typeahead-users" value="" />
    </div>
</div> 

Template.viewUsers.rendered = function() {
    var users = new Bloodhound({
      datumTokenizer: function(d) {
        return Bloodhound.tokenizers.whitespace(d.username);
      },
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      limit: 20,
      remote: {
        // url points to a json file that contains an array of tokens
        url: function() { 
          return Meteor.users.find().fetch().map(function(user){ return user.username; }); 
        }
      }
    });

    users.initialize();// kicks off the loading/processing of `local` and `prefetch`

    // passing in `null` for the `options` arguments will result in the default
    // options being used
    $('#tokenfield-typeahead-users').tokenfield({
      typeahead: [null, { 
        name: 'users',
        displayKey: 'username',
        source: users.ttAdapter() 
        // `ttAdapter` wraps the suggestion engine in an adapter that
        // is compatible with the typeahead jQuery plugin
      }]
    });
};

I prefer not to build an API, but if I have to, how do I provide the data?

4

2 回答 2

0

此代码发布 使用:

    local: [{ val: 'dog' }, { val: 'pig' }, { val: 'moose' }],
于 2015-06-25T11:48:16.590 回答
0

花相当多的时间尝试让tokenfield我的 Meteor 集合反应性地工作,所以我也会在这里发布我的解决方案。

我最终根本没有使用 Bloodhound,而是直接使用 Meteor。我意识到 RegEx 搜索非常原始,但如果您搜索的是标签集合,它就可以完成工作。

var currentTags = []; // Handle this however you wish

$('#tokenfield').tokenfield({
    typeahead: [null, {
        name: 'tags',
        displayKey: 'value',
        source: function(query, syncResults, asyncResults) {

            var suggestedTags = Tags.find({value: {
                $regex: "^"+query,
                $options: "i",
                $nin: currentTags
            }}).fetch();

            syncResults(suggestedTags);
            //Optionally do some server side lookup using asyncResults
        }
    }]
});
于 2015-11-18T11:46:02.810 回答