Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Developing a jQuery plugin that returns a given object, instead of jQuery object itself!

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.

like image 458
user307102 Avatar asked Dec 29 '25 19:12

user307102


1 Answers

(function($) {
    function MyApi($this, settings) {
        this.$this = $this;
        this.settings = settings;
    };

    MyApi.prototype.output = function (val) {
       // use this.$this to access the original jQuery object

       return this.settings[val];
    };

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

Note that we've passed this from $.fn.myPlugin() into the MyApi constructor; this allows you to access the jQuery object that myPlugin() was originally called on within MyApi methods.

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

(function($) {
    $.fn.myPlugin = function(settings) {
        return {
            settings: settings,
            output: function (val) {
                // use this.$this to access the original jQuery object

                return this.settings[val];
            },
            $this: this
        };
    };
});

Then;

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

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

... again, we've captured the value of this (the jQuery object) into a property $this on the newly constructed objected, to gain access to the original jQuery object.

like image 190
Matt Avatar answered Jan 01 '26 12:01

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!