About
backbone-autocomplete extends the backbone.js MVC library to allow users to create a simple auto-completing search form. This particular fork adds prefix exclusion (i.e. 'the', 'a'), which is pretty useful to have sometimes when searching things like titles of works. Documentation and code annotation is also a little better.Demo
Selected:
Download
Usage
All you need is an input element (+ Backbone libraries).
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"></script> <script type="text/javascript" src="backbone.autocomplete.js"></script> <form action="#"> <input type="text" id="search" /> </form>
Create a method called `label` on your model. This should return the string that the autocompleter searches against.
var PersonModel = Backbone.Model.extend({ label: function () { return this.get("name"); });
Create a collection for auto-completion model.
var PeopleCollection = Backbone.Collection.extend({ model: PersonModel }); var People = new PeopleCollection() People.add([ {name: "John Smith"}, {name: "John Rolfe"}, {name: "Govenor Ratcliffe"}, {name: "Pocahontas"}, {name: "Kocoum"} ]);
Initialize the AutoCompleteView in your view.
new AutoCompleteView({ input: $("#search"), model: People }).render();
Model URL support
In more realistic applications, the data you are searching against is on the server, not cached in the client browser. If you define a url in your backbone model, the widget will call yourModel.fetch({'query': 'current-text-you-have-typed-in'})
when appropriate. This query object can be handled directly by backend databases like MongoDB or Redis.
Additional Options
new AutoCompleteView({ input: $("#search"), model: People, className: 'autocomplete',//classname of the generated popup menu wait: 200,//throttling time (ms) minKeywordLength:2,//minimum keyword length queryParameter:'query',//search parameter for backend - have this if you are searching in the server onSelect: function(person){ $('#selectedPerson').show().html(person.label()) },//callback function for selected item excludedPrefices: ['The', 'A']//array of prefixes to exclude (search won't trigger if you type in 'The' first) //default excludes ['The', 'A'] }).render();