How do I expose public properties using jQuery plugins?

I am creating a small plugin using jQuery, but I want some of its data to appear as public. For example:

$(function () {
        $("#example1").myPlugin({
            exampleData: 'bar'
        });
        $("#example2").myPlugin({
            exampleData: 'foo'
        });
        $("#example3").myPlugin({
            exampleData: 'too'
        });

        $('.click').click(function () {
            console.log($("#example1").myPlugin('getData'));
            console.log($("#example2").myPlugin('getData'));
            console.log($("#example3").myPlugin('getData'));
        });
    });

      

I want the output on the console to be like this:

'bar'
'foo'
'too'

      

I tried to accomplish this with the following code:

(function ($) {
$.myPlugin = function (options) {
    $.myPlugin.settings = $.extend({
        exampleData: 'default value'
    }, options);
}

$.fn.myPlugin = function (methodOrOptions) {
    var methods = {
        getData: function () {
            return $(this).settings.exampleData;
        },
        init: function (options) {
            new $.myPlugin(options);
        }
    }

    if (methods[methodOrOptions]) {
        return methods[methodOrOptions].apply($(this), Array.prototype.slice.call(arguments, 1));
    } else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
        return methods.init.apply($(this), arguments);
    } else {
        $.error('Method ' + methodOrOptions + ' does not exist on jQuery.myPlugin');
    }
};
})(jQuery);

      

But I am getting "Cannot get property exampleData" from undefined or null reference

Can anyone help me with this?

+3


source to share


1 answer


The main problem is this line:

return $(this).settings.exampleData;

      

$(this)

returns a jQuery set and jQuery sets have no property settings

.

The main thing to remember when writing a plugin is that you are calling with a jQuery set, but whatever you do should only work on subsets of that set. Example:

// Initialize on a set that includes *all* paragraphs
$("p").myPlugin();

// ...

// But now we do something with just the third paragraph; the
// plugin should expect that and store information on a per-
// element basis, not a per-set basis
$("p").eq(2).myPlugin("doSomething");

      



One fairly straightforward way to do this is to store information using a jQuery function data

.

For what it's worth, here's an example of a basic plugin with "setData" and "getData" methods. Details in the comments in the code:

(function($) {
    "use strict";

    // Defaults
    var defaults = {
        // ...
    };

    // Methods
    var methods = {
        // (Note that `initialize` isn't on this list)
        getData:    getData,
        setData:    setData
    };

    // Utils
    var slice = Array.prototype.slice;

    // Expose the plugin
    $.fn.myPlugin = myPlugin;

    // Main entry point to plugin
    function myPlugin(arg) {
        var args = slice.call(arguments, 0);
        var method;
        var rv;

        // What are we doing?
        switch (typeof arg) {
            case "undefined":
            case "object":
                // Initializing
                rv = initialize.call(this, args);
                break;

            case "string":
                // Method, do we know it?
                method = methods[arg];
                if (!method) {
                    throw new Error("myPlugin: Unknown method '" + arg + "'");
                }
                args.shift(); // We've consumed the method name

                // Do it, return whatever it returns
                rv = method.call(this, args);
                break;

            default:
                throw new Error("myPlugin: Expected string or object as first argument if argument given.");
        }

        return rv;
    }

    // Initialize the plugin
    function initialize(args) {
        // Get the options
        var options = $.extend({}, defaults, args[0]);

        // Loop through, initializing the elements
        this.each(function() {
            // ...
            // (if appropriate here, you might detect whether you're being re-initialized
            // for the same element)
        });

        // Enable chaining
        return this;
    }

    // Get data
    function getData(args) {
        // "Get" operations only apply to the first element
        // Return the data; normally `args` wouldn't be used
        return this.first().data("myPlugin");
    }

    // Set data; "set" operations apply to all elements
    function setData(args) {
        this.data("myPlugin", args[0]);
        return this;
    }
})(jQuery);

      

Live example

+3


source







All Articles