Last active
June 22, 2016 08:19
-
-
Save fonji/5f5a71cf247fcb9e4098 to your computer and use it in GitHub Desktop.
select2 editor for Backbone-forms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Select2 editor for backboneforms | |
* https://gist.github.com/fonji/5f5a71cf247fcb9e4098 | |
* | |
* Renders Select2 - jQuery based replacement for select boxes | |
* Based on: | |
* https://gist.github.com/jbugwadia/9303389 | |
* | |
* Usage: Works the same as Select editor, with the following extensions for Select2: | |
* schema.config: configuration object passed to Select2 | |
* schema.multiple: sets 'multiple' property on the HTML <select> | |
* | |
* Example: | |
* schema: {title: {type:'Select2', options:['Mr','Mrs',Ms], config: {}, multiple: false} | |
* | |
* Also see: | |
* https://gist.github.com/powmedia/5161061 | |
* https://gist.github.com/Integral/5156170 | |
* Changelog: | |
* removed hard tabs (@fonji) | |
* added blur and focus events (fonji) | |
* delayed blur event (fonji) (it was fired when an element was clicked on) | |
* debug setValue and header misc (fonji) | |
* added focus() | |
* added getValue() to return an array when multiple | |
*/ | |
Backbone.Form.editors.Select2 = Backbone.Form.editors.Select.extend ({ | |
events: { | |
'select2-blur': function(event) { | |
if (!this.hasFocus) return; | |
var self = this; | |
setTimeout(function() { | |
if ($('#s2id_'+self.id).hasClass('select2-container-active')) return; | |
self.trigger('blur', self); | |
}, 100); | |
}, | |
'select2-focus': function(event) { | |
this.trigger('focus', this); | |
}, | |
'change': function(event) { | |
this.trigger('change', this); | |
} | |
}, | |
render: function() { | |
this.setOptions(this.schema.options); | |
var multiple = this.schema.multiple; | |
var config = this.schema.config || {}; | |
var elem = this; | |
setTimeout(function() { | |
if (multiple) { | |
elem.$el.prop('multiple', true); | |
} | |
elem.$el.select2(config); | |
}, 0); | |
return this; | |
}, | |
setValue: function (value) { | |
this.value = value; | |
// this is needed for init, before the callback in render | |
this.$el.val(value); | |
// this is needed for updates | |
this.$el.select2('val', value, true); | |
}, | |
getValue: function() { | |
var multiple = this.schema.multiple; | |
var value = this.$el.val(); | |
if (!multiple || _.isArray(value)) | |
return value; | |
if (!value) // matches null, undefined and '' | |
return []; | |
return value.split(','); | |
}, | |
focus: function() { | |
this.$el.select2('open'); | |
}, | |
disable: function() { | |
this.$el.select2('readonly', true); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment