I'm working on creating a new jQuery modal plugin. I'm pretty good at jQuery but still pretty new to the whole object oriented plug-and-play style of plugins so I used a different plugin I found online and ripped it apart using it as a foundation to build mine. However, I don't feel like I'm taking full advantage of it and not using the whole object-oriented "self" declaration correctly.
Plugin:
(function ($) {
var DasBtnResponse = {
Close: "close",
CloseNegative: "negative-close",
ClosePositive: "positive-close"
}
var methods = {
init : function (options) {
var self = this;
var settings = $.extend({
closeable: true,
size: "medium",
}, options || {});
this.each(function () {
self.data('plugin', settings);
});
methods.setup(this);
methods.setupButtons(this.find(".DasBtn"));
return this;
},
setup : function (elem) { //Set up the nav DOM elements
$data = elem.data('plugin');
self.wrapper = $("<div />")
.addClass("DasModalWrapper")
.click(function(e){
if (e.target === this && $data.closeable)
$(this).removeClass('open');
})
elem.replaceWith(wrapper);
wrapper.append(elem);
if ($data.closeable){
close = $("<div />")
.addClass("DasClose")
.html('×')
.click(function(e){
wrapper.removeClass('open');
})
.prependTo(elem.find('.DasModalHeader'));
}
},
open: function (elem){
$(elem).parent('.DasModalWrapper').addClass('open');
},
setupButtons : function (btns){
btns.each(function(i, obj) {
$btn = $(obj);
switch($btn.data('response')) {
case DasBtnResponse.Close:
$btn.on("click", function(){alert("close")})
break;
case DasBtnResponse.CloseNegative:
$btn.on("click", function(){alert("negative")})
break;
case DasBtnResponse.ClosePositive:
$btn.on("click", function(){alert("positive")})
break;
default:
break;
}
});
}
};
$.fn.initModal = function () {
methods.init.apply(this, arguments);
}
$.fn.openModal = function () {
methods.open(this);
}
})(jQuery);
Init/open example:
$(function(){
$("#modal").initModal({
closeable : true
});
})
$(document).on("click", "#launchModal", function(){
$("#modal").openModal();
});
Basic (empty) HTML Structure:
<div id = "modal" class="DasModal">
<div class="DasModalHeader"></div>
<div class="DasModalBody"></div>
<div class="DasModalFooter">
<div class="DasBtn btnDefault" data-response="close">Cancel</div>
<div class="DasBtn btnNegative" data-response="negative-close">No</div>
<div class="DasBtn btnPositive" data-response="positive-close">Ok</div>
</div>
</div>
My main concerns is that I want to avoid directly calling DOM elements/classes as much as possible e.g. this.closest('.wrapper');
and try to use variables instead. Also, there will be many more setting/options and functions this is just the foundation.