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?
This code posting uses:
local: [{ val: 'dog' }, { val: 'pig' }, { val: 'moose' }],
Spend quite some time trying to get the tokenfield
to work reactively with my Meteor collection, so I'll just post my solution here as well.
I ended up not using Bloodhound at all, but instead just using Meteor directly. I realize that the RegEx search is pretty primitive, but if what you're searching is a collection of tags, it does the job.
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
}
}]
});
来源:https://stackoverflow.com/questions/26760419/use-meteor-collections-for-typeahead-bloodhound-preferably-without-making-my-ow