Skip to content

Instantly share code, notes, and snippets.

@jkappers
Last active December 17, 2015 22:29
Show Gist options
  • Save jkappers/5682025 to your computer and use it in GitHub Desktop.
Save jkappers/5682025 to your computer and use it in GitHub Desktop.
Convert javascript class to jQuery plugin.
var camelize = function(str) {
return str[0].toLowerCase() + str.replace(/-([a-z])/g, function(a, b) { return b.toUpperCase(); }).slice(1);
}
var pluginize = function(classname, context) {
var camelized = camelize(classname)
$.fn[camelized] = function(config){
if (!this.length) return;
return this.each(function(){
var $element = $(this)
$element.data(camelized, new context[classname]($element, config));
})
}
}
<div id="view"></div>
<script>
// Wire it up...
$('#view').userRegistrationView({ bar: false })
// Retrieve the instance of UserRegistrationView later..
$('#view').data('userRegistrationView')
</script>
(function(exports){
function UserRegistrationView($element, config){
this.$element = $element
this.config = $.extend({}, UserRegistrationView._defaults, config)
this.init()
}
UserRegistrationView.prototype.init = function(){
// Initialize things...
}
UserRegistrationView._defaults = {
foo: 1,
bar: true
}
exports.UserRegistrationView = UserRegistrationView
pluginize("UserRegistrationView", exports)
})(window)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment