Kcko
2/27/2020 - 8:19 AM

Common jQuery pattern

var $ = jQuery.noConflict();

var Plugin = function($self, options) {
    this.$self = $self;
    this.options = $.extend({}, $.fn.plugin.defaults, options);
};

Plugin.prototype.init = function() {
    this.$self.css('color', this.options.color);
};

Plugin.prototype.update = function(newText, author) {
    this.$self.html(newText, author);
};

$.fn.plugin = function(option) {
    var options = typeof option == "object" && option;
    var data = arguments
    
    return this.each(function() {
        var $this = $(this);
        var $plugin = $this.data("plugin");

        if (!$plugin) {
            $plugin = new Plugin($this, options);
            $this.data("plugin", $plugin);
        }

        if (typeof option == 'string') {
            $plugin[option].apply($plugin, Array.prototype.slice.call( data, 1 ));
        } else {
            $plugin.init();
        }
    });
};

$.fn.plugin.defaults = {
    color: "black"
};


// usage
var p1 = $('p').eq(0).plugin();
var p2 = $('p').eq(1).plugin({
    color: 'red'
});

p2.plugin('update', 'This is a new text', 'by some author');