1

您好,我刚开始接触 JQuery 插件,但我在理解命名空间时遇到了一些问题。

给定下面的示例,当我输入“提交”函数时,如何在提交函数中获取原型实例?像“var self = this;” 在其他功能?该方法中的 this 指的是表单元素。

(function ($, window, document, undefined) {
    var PluginPrototype = {
        init: function (options, element) {
            var self = this;

            $(element).find('form').submit(self.submit);
            self.otherMethod();
        },

        submit: function(){
            var self = this; // the form element
        },

        otherMethod: function () {
            var self = this; // the prototype
        },
    }

    $.fn.pluginname = function (options) {
        return this.each(function () {
            var plugin = Object.create(PluginPrototype);
            plugin.init(options, this);

            $.data(this, 'pluginname', comment);
            // Get it by 
            // $.data($(select)[0], 'comment');
        });
    };

    $.fn.pluginname.Settings = {

    };
}(jQuery, window, document));
4

1 回答 1

2

实际上,这里有一些被误解的概念:

  1. 在您的情况下没有“原型实例”。当函数用作构造函数时,原型是函数的属性。在您的情况下,PluginPrototype 只是一个普通对象,它的原型是 Object.prototype。

  2. “this”是一个包含当前函数执行上下文的关键字,可以根据调用给定函数的方式进行修改。

  3. 我建议在这里阅读一些关于 jQuery 插件开发的信息:http ://learn.jquery.com/plugins/

也就是说,我可以建议一种典型的方法:

  1. 将插件的所有方法作为“方法”对象的属性(您当前的PluginPrototype

  2. 在 $.fn.pluginName 函数中实现逻辑来处理不同的执行请求。

    return this.each(function() {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(parameters, 1));
        } else if ( typeof method === "object" || ! method ) {
            return methods.init.apply(this, parameters);
        } else {
            $.error("Method "+method+"does not exist on my wonderful plugin");
        }
    });
    

    一个。通过 $("...").plugin({option: value, ...}); 调用插件初始化

    湾。插件方法通过 $("...").plugin("method name", argument1, argument2, ...); 调用

  3. 所有方法都将被调用,“this”指向当前 jQuery 包装的 dom 元素;因此,要从另一个方法内部调用一个方法,您将使用:

    methods.methodName.call(this, argument1, argument2);
    

希望这对您有所帮助。

于 2013-05-13T17:50:57.460 回答