Kaushik
Kaushik

Reputation: 3381

Adding functions to jquery custom plugin

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?

Upvotes: 3

Views: 150

Answers (3)

Stphane
Stphane

Reputation: 3456

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);

Upvotes: 1

Sudharsan S
Sudharsan S

Reputation: 15393

you missed the open and close the brace for the function . the function come like this $.fn.extend is Merge the contents of an object onto the jQuery prototype to provide new jQuery instance methods.

<div id="someDiv"></div>

jquery

jQuery.fn.dialog = (function() {
    alert("a");
});

$("#someDiv").dialog();

Fiddle

Upvotes: 0

Mukesh
Mukesh

Reputation: 858

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.

Upvotes: 1

Related Questions