Skip to content

Instantly share code, notes, and snippets.

@powmedia
Created October 12, 2012 16:03
Show Gist options
  • Save powmedia/3879951 to your computer and use it in GitHub Desktop.
Save powmedia/3879951 to your computer and use it in GitHub Desktop.
Backbone Forms custom editor for Ajax Chosen select
/**
* Creates an ajax-chosen instance
* @see https://github.com/powmedia/ajax-chosen
*
* @param {String} options.schema.queryUrl URL for ajax queries
* @param {Function} options.schema.itemToString Function that takes an item and returns how it should be displayed
*/
module.exports = Backbone.Form.editors.Select.extend({
render: function() {
Backbone.Form.editors.Select.prototype.render.call(this);
var self = this,
schema = this.options.schema,
queryUrl = schema.queryUrl,
itemToString = schema.itemToString;
//Create the chosen instance
function create() {
self.$el.ajaxChosen({
minLength: 1,
queryLimit: 50,
delay: 200,
chosenOptions: {
allow_single_deselect: false
},
searchingText: 'Searching...',
noresultsText: 'No results found.',
initialQuery: false
}, function(options, response, event) {
$.getJSON(queryUrl, { q: options.term }, function(data) {
var options = {};
_.each(data.items, function(item) {
options[item.id] = itemToString(item);
});
response(options);
});
});
}
//Trigger chosen once the select has actually been added to the DOM
setTimeout(create, 250);
return this;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment