Home » Jquery » In a custom jquery plugin how do I access the parent plugin from within an event on an element created and bound within the plugin init-Exceptionshub

In a custom jquery plugin how do I access the parent plugin from within an event on an element created and bound within the plugin init-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I’m trying to create an event handler within for a dynamically created element that can access the plugins other functions.

A simplified example:

;
(function($, window, document, undefined) {
/*main plugin*/
var pluginName = "myPlugin",
    defaults = {
        mySelectValue:'',
    }

function Plugin(element, options) {
    this.element = $(element);
    this.settings = defaults;
    $.extend(this.settings, options);
    this._defaults = defaults;
    this._name = pluginName;


    this.init();
}


Plugin.prototype = {
    init: function() {
        $(element).html('<div><a href="#" id ="myButton">My New Button</a> <select id ="mySelect"><option value="1">1</option><option value="2">2</option></select></div>');
        //bind events
        $('#myButton', this.element).on('click', function(event) {
            //how do I access  this.buttonHandler, when this reffers to my new button element
        });
        $('#mySelect', this.element).on('click', function(event) {
            //how do I access  this.selectHandler, when this now reffers to my new button element

        });
    },


    buttonHandler:function(){
        //do somestuff 
    },


    selectHandler:function(){
        //do somestuff 
    },

}

$.fn[pluginName] = function(options) {
    return this.each(function() {
        if (!$.data(this, "plugin_" + pluginName)) {
            $.data(this, "plugin_" + pluginName,
                new Plugin(this, options));
        }
    });
};

})(jQuery, window, document);

That is it, when binding the event ‘this’ now refers to the element being bound to, so how do I access the parent plugins properties and functions within on ‘..’ function?

How to&Answer: