Variable scope in a jQuery plugin?

2019-09-01 12:08发布

问题:

I continue a question, what I previously asked. It was a too simple sample :)

There is a plugin, what's syntax often used nowadays. I want to create an element at the initialization, and I want access to it from another methods. In the example below, I put it's declaration pretty deeply, but if I put it outside the init method, the open method drop an error, because it can't find it. (I'm not sure am I call the methods from another in the right way...)

(function($, window, document, undefined) {

        var opt = {
            text : 'sample'
        };
    var methods = { 
        init: function(options) {
            var self = $(this);

            if (options) {
                $.extend(opt,options);
            }
            return this.each(function () {
                var container = $('<div class="container" />');

                container.text(opt.text);
                $(this).append(container);
                $(this).click(function() {
                    self.pluginName('open');
                });
            });
        },
        open: function(args) {
            container.text('opened');
        },
        submit: function(args) {
            // call another method...
        }
    };

    jQuery.fn.pluginName = 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.pluginname');
        }
    };
})(jQuery, window, document);

I would like to call it any of number element, like this:

$(function() {
   $('div').pluginName();
});