开发者

jquery plugin where input can be options, method name, or method name with options

开发者 https://www.devze.com 2023-02-09 13:34 出处:网络
I have a plugin declared like this. (function ($) { var settings = { setting 1: undefined }; var methods = {

I have a plugin declared like this.

(function ($) {
    var settings = {
        setting 1: undefined
    };

    var methods = {
        init: function (options) {
            var data = $(this).data('myPlugin');

            if (!data) {
                //initialize plugin

                $(this).data('myPlugin', {
                    setting1: settings.setting1
                });
            }
        },
        doS开发者_运维问答omething: function() {
            //...do some work
        }
        sendData: function(data) {
            //TODO: Post data to the server
        }
    };

    $.fn.myPlugin = function (options) {

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

})(jQuery);

This works great when I use it like this

$('#myId').myPlugin({ setting1 : 'someValue' });

and when I want to do something like

$('#myId').myPlugin('doSomething');

but how can I modify the above code to support this...

var myData = 'some data';
var moreData = 'some more data';
$('#myId').myPlugin('sendData', { data: myData, moreData: moreData } );

...where I can pass in whatever I want as a second parameter and have that parameter passed along to the function?


something like this should work (nice it up where appropriate)

if( typeof options == "object" ) {
  // settings
} else {
  // action (better to explicitly check for string and undefined though)
  if( arguments.length > 1 ) {
     var action_options = arguments[1];
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消