0

我有一个带有函数的 JQuery 扩展,我不确定如何访问实例的选项:

    (function ($) {

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

    var methods = {
        init: function (options) {
            var defaults = {
                testOption: "test"
            };
            options = $.extend(defaults, options);

            return this.each(function () {
                 // Code logic goes here
            }

        MyFunction: function () {
            var optionVal = options.testOption;
        }
    };

})(jQuery);

因此,当我调用 MyFunction 时,此代码会引发错误,因为它不知道“选项”是什么。

4

2 回答 2

1

将其存储在元素的数据对象中。http://jsfiddle.net/U7QT5/

(function ($) {

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

    var methods = {
        init: function (options) {
            var defaults = {
                testOption: "test"
            };
            return this.each(function () {
                var $this = $(this);
                $this.data("MyExtension",$.extend(defaults, options));
                // Code logic goes here
            });
        },
        MyFunction: function () {
            var optionVal = this.data("MyExtension").testOption;
            console.log(optionVal);
        }
    };

})(jQuery);

$("body").MyExtension({testOption: "foobar!"}).MyExtension("MyFunction");
于 2013-05-08T18:32:44.683 回答
0

所以,我相信这只是一个简单的范围界定问题。您将对象选项传递给init,但它是该函数的本地选项。您需要将它放在对象上,以便您的其他功能MyFunction具有范围。

var methods = {
    init: function (options) {
        var defaults = {
            testOption: "test"
        };
        this.currentOptions = $.extend(defaults, options);

        return this.each(function () {
             // Code logic goes here
        }

    MyFunction: function () {
        var optionVal = this.currentOptions.testOption;
    }
};
于 2013-05-08T18:30:42.457 回答