views:

50

answers:

1

Hi, Consider the following base code:

(function($) {
    $.fn.myPlugin = function(settings) {
        return this.each(function() {
            //whatever
        });
    };
});

The plugin returns a jQuery object. The question is how am I supposed to write a plugin that returns a custom object so that I can do something like this:

var api = $('div.myelement').myPlugin();
api.onMyEventName(function(e, whateverParam) {
    //whatever
});

It'd be highly appreciated if you could write some lines of code that describes me how to do that, how to call the onMyEventName function on a custom api object...

Thanks.

+4  A: 
(function($) {
    function MyApi(settings) {
        this.settings = settings;
    };

    MyApi.prototype.output = function (val) {
       return this.settings[val];
    };

    $.fn.myPlugin = function(settings) {
        return new MyApi(settings);
    };
});

You can also do the same using the object literal syntax:

(function($) {
    $.fn.myPlugin = function(settings) {
        return {
            settings: settings,
            output: function (val) {
                return this.settings[val];
            }
        };
    };
});

Then

var something = $('#something').myPlugin({
   val: 'Lemon'
});

alert(something.output('val')); // Lemon
Matt