I've a custom plugin in jQuery,
jQuery.fn.dialog = function() {
return this.each(function() {
// Create dialog
});
};
Now I want to add a function such that it can be called like this:-
$("#somediv").dialog.showMe();
I tried doing this:-
jQuery.fn.dialog.showMe = function() {
$(this).show();
// some code
};
But I think here this is not the div, so $(this).show() is not working.
How can I achieve this? Are there any better ways of adding functions to jQuery plugins?
I coded a dialog factory base like what you are looking for ...
Feel free to ask if you have any question.
Test's fiddle here
// Dialog box factory base
(function ($) {
// kind of private vars
var dialog = function (opt, html) {
this.domElt = $('<div />', {
class: 'dialog-container'
}).append(html);
return this.init(opt);
},dialogsStack = [];
dialog.prototype = {
init: function (options) {
dialogsStack.push(this);
this.params = $.extend(this.params, options, {
dialogsIndex: (dialogsStack.length - 1)
});
console.log(this.params);
},
remove: function (all) {
var dis = this;
this.domElt.remove();
if (dialogsStack.length)
if (all) {
$.each(dialogsStack, function (i, el) {
el.domElt.remove();
// delete el;
});
dialogsStack = [];
} else {
this.domElt.remove();
console.log('rm: ' + this.params.dialogsIndex);
dialogsStack.splice(this.params.dialogsIndex, 1);
}
},
showMe: function () {
this.domElt.appendTo('body');
}
};
$.fn.dialog = function (options) {
var t = this.eq(0);
return new dialog(options, $('<div />').append(t).html());
};
})(jQuery);
You should add new method inside dialog:
jQuery.fn.dialog = function() {
this.showMe: function(){
$(this).show();
}
};
You can call this like:
var myDiv = $('#myDiv').dialog();
myDiv.showMe();
Or you can extend the current dialog and add method and use in same way above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With