JSFiddle - React, Tailwind, and code Playground

by hendrikdegraaf

HTML

<div class="doSomething"></div>

CSS

.doSomething {
    width: 200px;
    height: 50px;
    background-color: blue;
    cursor: pointer;
}

JavaScript

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

    // Create the defaults once
    var pluginName = "myplugin",
        defaults = {
            settingA: 'someValue',
            settingB: 'someValue'
        };

    // The actual plugin constructor
    function Plugin(params) {
        params.options = $.extend({}, defaults, params.options);
        this.params = params;
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    Plugin.prototype = {
        init: function () {
            this.cacheElements();
            this.bindEvents();
        },
        cacheElements: function () { //cache elements
            this.$el = $('div.doSomething');
        },
        bindEvents: function () {
            // To make the main plugin available in myFunction I need to pass it in the data
            this.$el.on('click', {base: this}, this.myFunction);
        },
        myFunction: function (event) {
            console.log(this); //this now refers to $el
            console.log(event.data.base); //This is a reference to my main plugin
        }
    };
    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function (params) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName,
                new Plugin(params));
            }
        });
    };

})(jQuery, window, document);

$(function () {
    $('div.doSomething').myplugin({
        settingA: 'someOtherValue'
    });
});