MrBoJangles
MrBoJangles

Reputation: 12237

Can I specify a method and an argument in a call to a jQuery function that I made?

Here's an example. It's a simple function created as per the docs here: http://docs.jquery.com/Plugins/Authoring.

(function ($) {
    var methods = {
        init: function (options) {
            // Gets called when no arg provided to myFunction()
        },
        doTask1: function () {
            // Do task #1
        },
        doTask2: function () {
            // Do task #2
        }
    };

    function HelperMethod(item) {
        // some handy things that may be used by one or more of the above functions
    }

    // This bit comes straight from the docs at http://docs.jquery.com/Plugins/Authoring
    $.fn.myFunction = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method == "object" || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error("Method " + method + " does not exist on jQuery.dcms");
            return null;
        }
    };
})(jQuery);

I may call the function like so: $('body').myFunction();, or $('body').myFunction("doTask1");

Is there an idiomatic and/or convenient way to, for example, change the preferences of a user, by calling the method like $('body').myFunction("changePref", "myPrefs");, or possibly $('body').myFunction("{changePref: myPrefs}");?

Or would I be better off just making a separate function just for user preferences that just takes the prefs as the argument?

Upvotes: 0

Views: 92

Answers (1)

MrBoJangles
MrBoJangles

Reputation: 12237

As it turns out, my init can handle any number of options. Furthermore, it's considered bad practice to make the separate function as that causes namespace clutter. See http://docs.jquery.com/Plugins/Authoring. under the heading Namespacing for some good documentation.

so here's a snippet, with a little commentary:

(function ($) {
    var methods = {
        init: function (options) {
            // Gets called when no arg provided to myFunction()
            // Also attempts to make use of whatever options provided if they
            // don't match the options below.
        },
        doTask1: function () {
            // Do task #1
        },
        doTask2: function () {
            // Do task #2
        }
    };
//...

I should be able to pass whatever argument(s) I want into myFunction() provided that I am handling them within the function.

Upvotes: 1

Related Questions