Created
November 20, 2013 22:28
-
-
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.
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
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