Variable scope in a jQuery plugin?

梦想的初衷 提交于 2019-12-13 04:43:04

问题


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();
});

来源:https://stackoverflow.com/questions/21853426/variable-scope-in-a-jquery-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!