I have a plugin that will open a modal every time a designated link is clicked. I attach the click event in the plugin's init() function, which then runs another of the plugin's functions.
The problem though is the plugin function called on click doesn't have access to other attributes of the plugin. It instead seems to be called within the scope of the window, not the plugin.
So in this example, toggleModal() has no access to this.config.container.
How do I trigger a plugin function on click, that stays within the plugin's scope?
The plugin is as below:
;(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);