JQuery plugin: how to call and maintain plugin function within scope on click
I have a plugin that will open the modal every time the assigned link is clicked. I attach a click event in the plugin init () function, which then triggers another of the plugin functions.
The problem is that the plugin function called by the click has no access to other plugin attributes. Instead, it is called within the window, not the plugin.
So, in this example, toggleModal () doesn't have access to this.config.container.
How do I call a plugin function on click that stays within the plugin scope?
The plugin looks like this:
;(function($, window, document, undefined){
var Modal = function(elem, options){
this.elem = elem;
this.$elem = $(elem);
this.options = options;
this.metadata = this.$elem.data('modal-options');
};
Modal.prototype = {
defaults: {
container: '#pageModal'
},
init: function() {
this.config = $.extend({}, this.defaults, this.options, this.metadata);
this.$elem.bind('click', this.toggleModal);
if(!$(this.config.container).length) {
this._build();
}
return this;
},
toggleModal: function() {
$(this.config.container).fadeIn();
return false;
},
_build: function() {
var structure = '<section id="' + this.config.container.replace('#', '') + '"><section class="modalContent"></section></section>';
$(structure).appendTo($('body')).hide();
},
}
Modal.defaults = Modal.prototype.defaults;
$.fn.modal = function(options) {
return this.each(function() {
new Modal(this, options).init();
});
};
})(jQuery, window, document);
+3
source to share