How to correctly implement option/update method in jquery plugin?

后端 未结 1 666
北恋
北恋 2021-01-14 23:37

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 he

1条回答
  •  再見小時候
    2021-01-15 00:06

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

    0 讨论(0)
提交回复
热议问题