|
-
Aug 5th, 2012, 01:16 PM
#1
Thread Starter
Hyperactive Member
"First" jQuery Plugin - Any critic / advice?
Hi,
I ended up last week with a really ugly piece of non reusable code where I basically wanted to open a modal, passing some data to it, and return data back when the modal close.
After some research I realized it's time to figure out how to create a jQuery plugin (something I always steered clear from, why I don't know)
Anyhow, here's some code I got working that I will be using in my "real" app at work and figured I post it here asking for some critic, tips and advice.
If anyone have a sec, have a look and let me know (I know it's annoying when someone post a lot of code...)
[Edit] just before posting I realized each subsequent time I open the modal, the callback function get called one more time. Ooops...something about bind/unbind no?
Code:
<div class="well">
<h3>Simple Modal using Plugin</h3>
<div>
Simply open a modal using a strongly typed partial view, but this time we use a jQuery Plugin that can be re-used (I hope)
</div>
<div>
Title:
<input type="text" id="txtTitle" placeholder="enter a title" />
</div>
<div>
Url:
<input type="text" id="txtUrl" placeholder="enter a url" />
</div>
<input type="hidden" id="modalReturnData"/>
<a href="#" id="showModal">Open Modal</a>
</div>
<!-- ***** Modal ***** -->
<div id="myModal" class="modal hide fade">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 id="modalTitle"></h3>
</div>
<div class="modal-body" id="modalContent">
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal" >Close</a>
</div>
</div>
<!-- ***** End Modal ***** -->
@section ViewScripts {
<script type="text/javascript">
$(document).ready(function () {
$('#showModal').click(function () {
$('#myModal').bootstrapModal(
{
title: $('#txtTitle').val(),
url: $('#txtUrl').val()
},
function (data) {
$('#modalReturnData').val(data.join(","));
alert($('#modalReturnData').val());
}
);
});
});
// todo: put in separate file...
(function($) {
$.fn.extend({
bootstrapModal: function(options, callback) {
var defaults = {
title: "default title",
url: "default url"
};
options = $.extend(defaults, options);
return this.each(function() {
$('#modalTitle', this).text(options["title"]);
$('#modalContent', this).text(options["url"]);
$(this).modal('show');
$(this).bind('hidden', function() {
if (typeof callback == 'function') {
// just some DEMO DATA, for instance will be id's of all selected checkboxes
var demoIds = new Array();
for (var i = 0; i < 5; i++) {
demoIds.push(i);
}
callback.call(this, demoIds);
}
});
});
}
});
})(jQuery);
</script>
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|