1
;(function ($, w, d, config, undefined) {
$.fn.pluginName = function ( options, config ) {
    var pluginName = this;
    var defaults = {
        //defaults
    };
    var settings = $.extend({}, defaults, options);

    var methods = {
        init :  function ( settings, options ) {
            //init stuff here
        }
    }
})
})(jQuery, window, document)

// HTML looks like this
<script>
$('.item').pluginName({ methods : 'init' });
</script>

我是插件开发和一般对象的新手,但我试图在没有游泳的情况下深入学习。:)

基本上,我想通过调用方法变量中的“init”函数来初始化我的插件。我的插件名称是“pluginName”。

我无法调用“init”fn,因为它位于名为“methods”的变量中。

此外,为了更进一步,我需要收集页面上的所有“项目”类并设置内部数据变量。在我的初始化函数中,我有以下内容:

return this.each(function(){

    var $this       = $(this),
    data        = $this.data('pluginName');

    if ( ! data ) {
        $(this).data('pluginName', {
        target : $this
        });

    }
}).bind(this);

以上返回“this.each 不是函数”

任何帮助,将不胜感激!非常感谢!!

4

1 回答 1

2

为了使您不必为方法调用传递对象,我通常使用以下格式:

(function($) {
    function doSomething() {
        // Only callable in this plugin's context (I think)
    }

    var methods = {
        init: function (options) {
            // Do whatever for init!
            doSomething();
        },

        anotherMethod: function (options) {
            // Some other method
            doSomething();
        }
    };

    $.fn.pollServer = function(method) {
        var args = arguments;
        var argss = Array.prototype.slice.call(args, 1);

        return this.each(function () {
            $this = $(this);
            if (methods[method]) {
                methods[method].apply($this, argss);
            }
            else if (typeof method === "object" || !method) {
                methods.init.apply($this, args);
            }
            else {
                $.error("Method " + method + " does not exist on jQuery.pollServer");
            }
        });
    };
})(jQuery);

And you access it like:

$("#div").pollServer({});
$("#div").pollServer("init", {}); // Same as above line

$("#div").pollServer("anotherMethod", {});

Everything inside of return this.each() determines what method to call, and set the "this" variable as the jQuery element selected. It also passes additional arguments to the methods.

Hope this helps!

于 2012-06-28T15:59:12.873 回答