Last active
December 17, 2015 22:29
-
-
Save jkappers/5682025 to your computer and use it in GitHub Desktop.
Convert javascript class to jQuery plugin.
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
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)); | |
}) | |
} | |
} |
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
<div id="view"></div> | |
<script> | |
// Wire it up... | |
$('#view').userRegistrationView({ bar: false }) | |
// Retrieve the instance of UserRegistrationView later.. | |
$('#view').data('userRegistrationView') | |
</script> |
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
(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