Skip to content

Instantly share code, notes, and snippets.

Created November 20, 2013 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/7572281 to your computer and use it in GitHub Desktop.
Save anonymous/7572281 to your computer and use it in GitHub Desktop.
A few things going on here... First, it shows how to create a class in JavaScript. It shows how to properly use `.bind()` to keep the `this` object working. It shows jQuery's `$.extend()` method to map options to a set of defaults.
window.MultiSelect = (function() {
function MultiSelect(options) {
var defaults = {
checkboxSelector: ".multi-select-checkbox",
onSelector: ".multi-select-on",
selectAllSelector: "#multi-select-all"
};
this.options = $.extend(defaults, options);
}
MultiSelect.prototype.hide = function () {
console.log("MultiSelect: hide");
$(this.options.onSelector).hide();
};
MultiSelect.prototype.initialize = function() {
this.hide();
this.listenForCheckedEvent();
};
MultiSelect.prototype.listenForCheckedEvent = function() {
// Be sure to call .bind() on the callback, otherwise the callback
// will have the context of the checkbox, not the class definition.
$(this.options.selectAllSelector).click(function() {
var isChecked = $(this.options.selectAllSelector).is(":checked");
this.toggleChecked(isChecked);
}.bind(this));
};
MultiSelect.prototype.setChecked = function (value) {
console.log("MultiSelect: setChecked(" + value + ")");
$(this.options.checkboxSelector).prop("checked", value);
};
MultiSelect.prototype.show = function () {
console.log("MultiSelect: show");
$(this.options.onSelector).show();
};
MultiSelect.prototype.toggleChecked = function(isChecked) {
if (isChecked) {
this.setChecked(true);
} else {
this.setChecked(false);
}
};
return MultiSelect;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment