如何正确实现jquery插件中的选项/更新方法?

时间:2022-02-02 14:30:32

I'm trying to create a plugin with ability to update options after initialization. I've started with simple plugin, which will help me to understand plugin's logic. So here it is:

我正在尝试创建一个插件,有能力在初始化后更新选项。我从简单的插件开始,这将帮助我理解插件的逻辑。所以在这里:

;(function($) {

    var defaults = {
        message: 'This is default message'
    };

    var options = {};

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

            return this.each(function() {

                $(this).click(function(){
                    alert(options.message);
                });

            });
        },

        option: function( key, value ){
                    if (val) {
                        options[key] = val;
                    } else {
                        return options[key];
                    }
                }
        };  

    $.fn.clickAlert = 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 {
            //some error that method doesnt exist
        }    
    };

})(jQuery);

As you can see, this plugin just show's alert message with defined text. Also, I have HTML page (where I include jquery library and this plugin) with 2 links:

正如您所看到的,这个插件只是显示了带有定义文本的警告消息。另外,我有HTML页面(其中包括jquery库和这个插件),其中有两个链接:

<a href="#" class="show">SHOW ALERT</a>
<a href="#" class="change">CHANGE ALERT MESSAGE</a>

I create an instance of 'clickAlert' plugin on link with "show" class. When I click on it, it shows default message as I expected. But I want (for example) to click on link with "change" class and update 'message' attribute of earlier created instance. BUT SOMETHING IS WRONG. My jquery code on HTML page:

我在“show”类的链接上创建了一个“clickAlert”插件的实例。当我点击它时,它会显示默认的消息。但我想(例如)点击“change”类的链接,并更新先前创建实例的“message”属性。但有些事情是错误的。我的jquery代码在HTML页面:

<script type="text/javascript">
jQuery(document).ready(function($) {

        $('.show').clickAlert();

        $('.change').click(function(){

            $('.show').clickAlert('option', 'message', 'Updated message');

        });

});
</script>

1) How to correctly implement option/update method in this jquery plugin?
2) I have one more question, but it's not related to main question. For example I will create plugin using this pattern. Besides init and option methods, plugin will have 10 more methods (for example) responsible for animation. In my init method I'll need to check, (using SWITCH statement) which animation method should I call and call it. Because I need to do this action more then one time, it's better to create one function in order to avoid code dublication. Where is the best place for creating function like this? Should I create it as a new method (like init, option and other animation methods) or I can simply create it in init's "return this.each()" function and also call it few times there?

1)如何正确实现这个jquery插件的选项/更新方法?我还有一个问题,但与主要问题无关。例如,我将使用这个模式创建插件。除了init和选项方法之外,插件还将有10个方法(例如)负责动画。在我的init方法中,我需要检查,(使用SWITCH语句)我应该调用哪个动画方法并调用它。因为我需要多次执行这个操作,所以最好创建一个函数,以避免代码生成。创建这样的函数的最佳位置在哪里?我应该将它创建为一个新方法(如init、option和其他动画方法),或者我可以简单地在init的“返回this.each()”函数中创建它,并在那里调用它几次?

1 个解决方案

#1


2  

It is a question of scope, you need to change the scope of the options - normally you would not but in this case you do, so you change to modify the original options in the $.extend(, and give it a reference thus:

这是一个范围问题,您需要更改选项的范围——通常情况下您不会,但是在这种情况下,您会更改,以修改$中的原始选项。扩展(,并给它一个参考:

;(function ($) {

    var self = this;
    self.defaults = {
        message: 'This is default message'
    };
    self.options = {};
    var methods = {
        init: function (options) {
            options = $.extend(self.options, self.defaults, options);
            return this.each(function () {
                $(this).click(function () {
                    alert(options.message);
                });
            });
        },
        option: function (key, myvalue) {
            if (myvalue) {
                self.options[key] = myvalue;
            } else {
                return self.options[key];
            }
        }
    };
    $.fn.clickAlert = 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 {
            //some error that method doesnt exist
        }
    };
})(jQuery);
jQuery(document).ready(function ($) {
    $('.show').clickAlert();
    $('.change').click(function () {
        $('.show').clickAlert('option', 'message', 'Updated message');
    });
});

#1


2  

It is a question of scope, you need to change the scope of the options - normally you would not but in this case you do, so you change to modify the original options in the $.extend(, and give it a reference thus:

这是一个范围问题,您需要更改选项的范围——通常情况下您不会,但是在这种情况下,您会更改,以修改$中的原始选项。扩展(,并给它一个参考:

;(function ($) {

    var self = this;
    self.defaults = {
        message: 'This is default message'
    };
    self.options = {};
    var methods = {
        init: function (options) {
            options = $.extend(self.options, self.defaults, options);
            return this.each(function () {
                $(this).click(function () {
                    alert(options.message);
                });
            });
        },
        option: function (key, myvalue) {
            if (myvalue) {
                self.options[key] = myvalue;
            } else {
                return self.options[key];
            }
        }
    };
    $.fn.clickAlert = 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 {
            //some error that method doesnt exist
        }
    };
})(jQuery);
jQuery(document).ready(function ($) {
    $('.show').clickAlert();
    $('.change').click(function () {
        $('.show').clickAlert('option', 'message', 'Updated message');
    });
});