Skip to content

Instantly share code, notes, and snippets.

@GuillaumeBiton
Created August 10, 2012 16:43
Show Gist options
  • Save GuillaumeBiton/3315478 to your computer and use it in GitHub Desktop.
Save GuillaumeBiton/3315478 to your computer and use it in GitHub Desktop.
Simple binding between Bootstrap typeahead and Backbone collection
Simple example on how to make Twitter Bootstrap typeahead working with backbone collections.
Usage :
var bui = new Bootstrap.Typeahead({
collection: ?
property: ?
items: ?
...
});
You can bind the event 'change' on this.$el in the initialize function, like this:
this.$el.on('change', function(e){ console.log(e.target.value)});
Be Careful: Not working in IE<10, sorry
var Bootstrap = {};
Bootstrap.Typeahead = Backbone.View.extend({
tagName: 'input',
attributes: {"data-provide": "typeahead"},
initialize: function(options){
if(!this.collection) {
console.log("Usage: new Bootstrap.Typeahead({collection: ?, property: ?, items: ?})\nif no property, it will use the first attribute");
return null;
}
var prepare = _.pluck(this.collection.models, 'attributes');
this.property = this.options.property || _.keys(prepare[0])[0];
this.items = this.options.items;
this.data = _.pluck(prepare, this.property);
},
render: function() {
this.$el.typeahead({
source: this.data,
items: this.items
});
return this
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment