Created
November 1, 2013 21:17
-
-
Save chiplay/7272109 to your computer and use it in GitHub Desktop.
Backbone.Stickit + Selectize.js Handler
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
define([ | |
'jquery', | |
'backbone', | |
'underscore', | |
'backbone.stickit', | |
'selectize' | |
], | |
function ($, Backbone, _) { | |
Backbone.Stickit.addHandler({ | |
// Custom handler for selectize.js select list | |
selector: 'select.selectize', | |
initialize: function($el, model, opt) { | |
var _this = this, | |
selectize, | |
$select, | |
options; | |
// Create a 'recent searches' optgroup for new items | |
var add = _.once(function() { | |
selectize.addOptionGroup('Recent Searches', {label: 'Recent Searches', value: 'Recent Searches'}); | |
}); | |
// Refresh after adding a new optgroup | |
var refresh = function() { | |
selectize.refreshOptions(); | |
}; | |
// Get view options | |
var getDefaultOptions = function(options) { | |
options = options || {}; | |
return _.defaults(options, { | |
highlight: false, | |
sortField: 'text' | |
}); | |
}; | |
options = getDefaultOptions(_.result(_this, 'selectize')); | |
// Call back when observed model attributes change | |
// Only need to initialize selectize once | |
var up = function(m, v, o) { | |
if (!selectize) { | |
$select = $el.selectize(options); | |
selectize = $select[0].selectize; | |
selectize.on('option_add', add); | |
selectize.on('optgroup_add', refresh); | |
} | |
}; | |
// Add listeners for each observable | |
_.each(_.flatten([opt.observe]), function(attr) { | |
var e = 'change:' + attr; | |
this.listenTo(model, e, up); | |
this.listenTo(model, 'stickit:unstuck', function() { | |
_this.stopListening(model, e, up); | |
}); | |
}, this); | |
// Destroy selectize when the view closes | |
this.on('close',function(){ | |
if (selectize) selectize.destroy(); | |
},this); | |
} | |
}); | |
return Backbone.Stickit; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment